0

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"
  class="form-control"
  name="amount"
  ng-pattern="{{ctrl.pattern}}"
  ng-model="ctrl.amount">

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?

1 Answer 1

1

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 ^,$

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That worked for me. I'm actually getting the regex from a translation file (need to replace the decimal separator depending on locale) so it has to be a string. I was able to convert the string to a RegExp object via the constructor new RegExp() and thus use your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.