Rushikesh Rushikesh - 1 year ago 163
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:


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 Source

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})$


^               ^ : 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})" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download