Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  171] [ 3]  / answers: 1 / hits: 5236  / 10 Years ago, thu, october 23, 2014, 12:00:00

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.


More From » regex

 Answers
10

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})$


[#41721] Wednesday, October 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mattieparisp

Total Points: 612
Total Questions: 109
Total Answers: 104

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;