Reputation: 2053
I've got an HTML5 pattern that works great for phone numbers in the following format:
111-222-3333
111 222 3333
(777)-888-9999
(777)888-9999
But if a user enters
(777-999-9999
It passes the validation. Ideally I'd want this to throw an error since the parentheses is clearly not closed. Here is my pattern:
pattern="^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$"
Any ideas on what I'm doing wrong? I've been banging my head against a wall for hours on this one. Thanks!
Upvotes: 7
Views: 25105
Reputation: 664503
The optionalities of the two parenthesis are independent of each other. Use an alternation:
pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}"
Upvotes: 16