Search code examples
angularjsng-pattern

Bypass default wrapping of ^and $ in ng-pattern


Im getting my regex from an API, and they often starts with ^ and ends with $ (for example ^-?[0-9]+$). Just putting the regex as a string to ng-pattern results in a Lexer Error, since angular adds the ^ and $ by default on strings.

From Angular API reference

  • If the expression evaluates to a RegExp object, then this is used directly.
  • If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. For instance, "abc" will be converted to new RegExp('^abc$').

Very well then, let's try to convert the regex string into a regex object, I thought. So I tried this:

json.data.data[i].validateRegex = new RegExp(json.data.data[i].validateRegex, "g");

But it result in another error:

Error: ngPattern:noregexp
Expected Regular Expression
Expected {} to be a RegExp but was {}.

How can I get my regex to work with ng-pattern? Preferably without removing the ^ and $ from the regex.


Solution

  • Converting the string to an regex object works.

    But ng-pattern shouldn't have {{ }} in it. Changing it from ng-pattern="{{ regexObj }}" to ng-pattern="regexObj" did the trick!