1

I'm using ng-pattern on a text field to validate a Canadian phone number:

^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

But AngularJS throws this error:

Syntax Error: Token '?' not a primary expression at column 3 of the expression [^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$] starting at [?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$].

I tested it, and tried it in a couple different online regex editors like Rubular, and it seems perfectly valid. I am creating the fields dynamically so ng-pattern is being set like this in the directive within ngRepeat.

ng-pattern="{{field.format}}"

if I change it to hardcoded regex it doesn't throw any errors:

ng-pattern="/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/"

But then I changed it to something ridiculously simple:

^[0-9]{3}$

And this works, so can't be dynamically created fields and related to just the regex.

1 Answer 1

3

Bonjour. The first ? doesn't have anything to quantify. Remove it. Which means that you also should remove the resulting extra parenthesis.

^([0-9]{3})?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

Ed. With optional brackets (actually parenthesis) for area code (untested):

^(\(?([0-9]{3})\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

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

2 Comments

thought that it would allow me to have brackets on the area code, so escaped them so it wasn't a grouping and added ? for 0 or 1 instances. you're solution does work, but how would you add the brackets?
Thanks, I just replaced the [] with (). I see what I was doing wrong.

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.