mtpultz
mtpultz

Reputation: 18248

AngularJS ng-pattern throws error on regex for phone number

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.

Upvotes: 1

Views: 5195

Answers (1)

sebnukem
sebnukem

Reputation: 8313

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

Upvotes: 3

Related Questions