Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 pattern for phone number with parentheses

Tags:

html

regex

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!

like image 741
Delmon Young Avatar asked Sep 18 '13 03:09

Delmon Young


1 Answers

The optionalities of the two parenthesis are independent of each other. Use an alternation:

pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}"
like image 55
Bergi Avatar answered Sep 22 '22 16:09

Bergi