Rushikesh Rushikesh - 1 month ago 6
Javascript Question

How to check pair of brackets condition using regular expression?

I am writing a java script in which I want to validate numbers of following format:

555-555-5555
(555)-555-5555


For this, I am using following regular expression:

/\(?(\d{3}\)?)[- ]?(\d{3})[- ]?(\d{4})/


But this is giving true for following expression which is wrong:

(555 - 555 5555


I want to make this regular expression to check if opening bracket is present then closing bracket must be present and vice versa. What changes should I do in my RE to make it achieve my goal?

Answer

As the braces are optional ?-zero or one occurrence, the regex is allowing ( and/or ) brace. OR condition in the regex can be use to match either three numbers or three numbers in brackets.

^(\(\d{3}\)|\d{3})[- ]?(\d{3})[- ]?(\d{4})$

Demo

(\(\d{3}\)|\d{3})
^               ^ : Group
 ^^     ^^        : Matches ( & ) respectively
          ^       : OR condition in regex
   ^^^^^   ^^^^^  : Match three digits

input:valid {
  color: green;
}
input:invalid {
  color: red;
  font-weight: bold;
}
<input pattern="(\(\d{3}\)|\d{3})[- ]?(\d{3})[- ]?(\d{4})" />