Regex to validate phone format in Javascript

In this post we will see javascript regular expression that will help us to check phone number in specific format. You may use the example and create a regex by modifying the same for date format or any other format or string. We will be using capture group and to understand the please take look at my article about named group.


Problem

We need to check if the provided date is in format ###-###-####. The phone number format will vary depending on the country. Also we are not considering country code here but yo may figure that out and then capture it accordingly. Also we will be only checking for ‘-‘ special character but you may check for other character as well by updating the regex below. We will use named capture and number capture here in regular expression. Below we create a regular expression and test the phone number string again it. We will use the test method of regular expression. If the output is ‘true’ that means the date is in required format. If output is ‘false’ then the date is not in the required format and we can throw an error here.

const dateRegex = /^(?:\d{3}|\(\d{3}\))([-])\d{3}\d{4}$/;

const wrongDateStr = '111-222-333';
dateRegex.test( wrongDateStr ); // Output false

const correctDateStr = '111-222-3333';
dateRegex.test( correctDateStr ); // Output true

Regular Expression explanation

/^(?:\d{3}|\(\d{3}\))([-])\d{3}\d{4}$/;
  • (?:\d{3}|\(\d{3}\)) – Here we create a non-capturing group and check for any number repeating 3 times.
  • ([-]) – Here we create a group and check if we get a ‘-‘ character. We will use this group using ‘\1’ ahead in the expression.
  • \d{3} – We check for any number repeating 3 times.
  • \1 – We repeat the group that we have created before explained in point number 2.
  • d{4}$ – Last we check for any number 4 times and it should be the last in string.

Conclusion

Hope you like the short explanation on how we can use a regular expression that will help us to verify date in specific format. Hope this helps you, see you in my next post. Till then enjoy coding 🙂