Spittal
Spittal

Reputation: 779

Regex Pattern Throwing a Lexer Error AngularJS

I'm getting a Lexer Error when using ng-pattern on an input element

My regex is to test phone-numbers and on the input it looks like this:

<input 
    type="text"
    class="phone"
    ng-pattern="(\(?([0-9]{3})\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})"
    placeholder="Phone Number" ng-model="contactFormVM.contact.phone"
    required />

And then Angular yells at me and gives me this error:

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

Now I can see it's getting angry about my \. However I don't know how to write the regex without escaping that. The funny thing is, the test actually works and it does validate correctly, but I hate throwing an error for nothing.

Any ideas as to why this is happening?

Thanks

Upvotes: 4

Views: 845

Answers (1)

Matthew Green
Matthew Green

Reputation: 10391

You would need to escape any \ in your string because ngPattern takes that string and wraps it in new RegExp('stringhere') which requires you to escape that character.

Upvotes: 5

Related Questions