Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-pattern should not match supplied pattern

In ng-pattern we have the option of specifying that the field should match a specific pattern.

How can we specify that it should NOT match the specified pattern?

Example,

<input type="text" ng-pattern="/[*|\":<>[\]{}`()';@&$]/" />

Here, I DONT want the field to match the pattern. On the contrary, I want to show error if the pattern matches.

like image 956
Tarun Dugar Avatar asked Sep 25 '22 18:09

Tarun Dugar


2 Answers

You could use a negative lookaround ((?!pattern)) to negate your regex:

ng-pattern="/(?![*|\":<>[\]{}`()';@&$])/"
like image 142
Darin Dimitrov Avatar answered Oct 03 '22 07:10

Darin Dimitrov


In order to check if a string does not have some substring, you can use a string-start-anchored lookahead:

/^(?!.*[*|\x22:<>[\]{}`()';@&$])/

See demo

In AngularJS, the pattern does not have to match the entire string if a RegExp object is passed (the one with delimiters), so this regex suits the current purpose well (just check if a condition is true or false).

Note that the commonly used tempered greedy token solution ^(?:(?![*|\x22:<>\[\]{}`()';@&$]).)*$ (see demo) can be used, too, but it is less efficient since each position in the input string is checked.

Also, it is convenient to use \x22 to match a double quote in the ng-pattern value.

like image 37
Wiktor Stribiżew Avatar answered Oct 03 '22 06:10

Wiktor Stribiżew