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!
The optionalities of the two parenthesis are independent of each other. Use an alternation:
pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With