1

with this code snippet I am trying to ensure that a textfield does not end with any of the letters outline in the $scope.pointPattern

$scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/;
            $scope.error = "not valid";

on running the code, only when the field ends with ess that the error is shown but other letters are never blacklisted

e.g 
football ess > shows error not valid
footbal ence > does not show error and likewise on sports and riding

what am I doing wrong

user10445503
  • 165
  • 10

1 Answers1

1

Your ^(?!.*ess|ence|sports|riding?$) regex matches a string that does not end with ess and that does not start with ence, sports, and does not end with riding and ridin. See your regex demo. That happens because the alternatives are not grouped and the $ only

You need to group these alternatives.

Use

$scope.pointPattern = /^(?!.*(?:ess|ence|sports|riding?)$)/;
                             ^^^   ^    ^      ^       ^

The (?! and the last ) define the boundaries of the negative lookahead and the (?:ess|ence|sports|riding?) is a non-capturing group that matches any of the alternatives listed inside it delimited with | (alternation operator).

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Had to group it using your solution and this worked for me $scope.pointPattern = /^(?!.*ess|.*ence|.*sports|.*riding?$)/; as well – user10445503 Oct 02 '18 at 15:46
  • @user10445503 Note it matches strings that do not contain `ess`, `ence`, `sports` and that do not end with `riding` or `ridin`. The `$` only refers to `.*riding?` alternative, other branches do not "see" the `$` anchor. – Wiktor Stribiżew Oct 02 '18 at 15:47
  • You are the regex king – user10445503 Oct 02 '18 at 15:52