Paul D. Paul D. - 1 year ago 139
AngularJS Question

Getting Lexer Error with AngularJS and ng-pattern

I'm getting the following error at runtime:

Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 11-11 [\] in expression [[0-9]{1,4}(\.[0-9]{1,3})?].

My HTML looks like this

<input type="text"

The assignment in my AngularJS controller is as follows:

ctrl.pattern = '[0-9]{1,4}(\\.[0-9]{1,3})?';

From what I understand AngularJS appends the ^ and $ at the beginning and end of regular expressions and that works great. The problem is that the regex literal in the middle of the expression is not being accepted. I want to dot to be accepted as a literal and not as any character so I need a way to escape it yet the lexer does not to like it. Is there a way around this?

Answer Source

This issue is already reported here but they are not going to fix it as according to them its a uncommon usecase.

Do it this way instead:

ctrl.pattern = /^[0-9]{1,4}([.][0-9]{1,3})?$/;

This way the regex will be evaluated as a regex object instead of a string parameter to RegExp in which case we will need to add ^,$

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download