HTML5 template for phone number with parentheses

I have an HTML5 template that works great for phone numbers in the following format:

111-222-3333 111 222 3333 (777)-888-9999 (777)888-9999 

But if the user enters

 (777-999-9999 

He is being tested. Ideally, I would like this to trigger an error, since the parentheses are clearly not closed. Here is my template:

 pattern="^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$" 

Any ideas on what I'm doing wrong? I banged my head against the wall for several hours. Thanks!

+6
source share
1 answer

The optional functions of the two brackets are independent of each other. Use alternation:

 pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" 
+13
source

Source: https://habr.com/ru/post/954031/


All Articles