user10445503
user10445503

Reputation: 165

ng-pattern to ensure that a textfield letter does not end with a specific word

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

Upvotes: 1

Views: 24

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

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).

Upvotes: 1

Related Questions