5

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.

Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
  • Do you want to use the same pattern? If yes, you'd need to create a custom validator. If not, you can use [`^(?:(?![*|\x22:<>\[\]{}\`()';@&$]).)*$`](https://regex101.com/r/nN8uK7/1), I think. – Wiktor Stribiżew Jan 04 '16 at 12:44
  • Looks like [that question](http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word) I linked to does not have the other regex I showed in my comment. I think I should reopen the question. – Wiktor Stribiżew Jan 04 '16 at 14:27

2 Answers2

3

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

ng-pattern="/(?![*|\":<>[\]{}`()';@&$])/"
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    This will not work. Here is [a test](https://regex101.com/r/hK7zK7/1). The lookahead does not match anywhere in the string, it will match right after the current position. `/[*|\":<>[\]{}\`()';@&$]/` matches any of the symbols inside the character class, the opposite should make sure there is no such symbols in the entire string. A correct regex will be `/^(?!.*[*|\":<>[\]{}\`()';@&$])/`. – Wiktor Stribiżew Jan 04 '16 at 12:53
1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563