4

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

1 Answer 1

5

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.

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

5 Comments

i.e. ng-pattern="(\\(?([0-9]{3})\\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})"
can you use ng-pattern=/(\(...\))/ or ng-pattern=(\(...\)) by any chance?
Pattern looks like this now ng-pattern="(\\(?([0-9]{3})\\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})" however I'm still throwing the exact same error: Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 1-1 [\] in expression [(\\(?([0-9]{3})\\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})].
@Aprillion you should be able to as the note on ngPattern says it looks for a regex object or else wraps the string into a regex object.
@Spittal you might try putting your regex in an object on the scope and reference it that way instead and see if you get different results. Otherwise, you might need to cook up an example snippet for everyone to look at to work this further.

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.