Delmon Young
Delmon Young

Reputation: 2053

HTML5 pattern for phone number with parentheses

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

Answers (1)

Bergi
Bergi

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

Related Questions