Phone Number Validation in JavaScript

Step by step guide to develop JavaScript methods to check for valid phone numbers

In a previous post, we learnt how to validate a phone number input field in a HubSpot contact form. Today, we are going to explore two solutions to validate phone numbers using JavaScript.

Solution #1: Phone Number Validation using JavaScript and Regex

The easiest way to validate phone numbers using JavaScript would be to use Regular expressions.

First off, we should make sure that the format validator should not only support  NANP (country code +1) numbers. The regex that we will use should allow for a phone number from outside North America.

However there are different formats of phone numbers depending on the user's preference and the country code and culture.

Here are some regular expressions to validate phone numbers using JavaScript:

If you just want to check for 10 digits then use the following regex:

var regex1 = /^\d{10}$/;

To apply one of these formats: xxx-xxx-xxxx, xxx.xxx.xxxx, xxx xxx xxxx then use the following regex:

var regex2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

If you want to use a + sign before the number in the following way: 

+xx-xxxx-xxxx or +xx.xxxx.xxxx or +xx xxxx xxxx

then use the following regex:

var regex3 = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;

Finally, here is the complete JavaScript function to validate a phone number with regex. Remember that client-side validation is only a convenience we provide to the user. JavaScript phone number validation is not a substitute for server-side validation, we still need to validate all input (again) on the server.

function ValidatePhoneNumber(txt) {
    var regex2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (txt.value.match(regex2)) {
        return true;
    } else {
        alert("Not a valid Phone Number");
        return false;
    }
}

Solution #2: Use libphonenumber JavaScript Library

In some cases, using a regular expression to validate complex real-world data like phone numbers can't cover all cases. That's why it is recommended to use a specialized library such as the libphonenumber.

Latest version of libphonenumber can be found on cdn here. In the following code, we added a reference to the library, then we used the extension function "asYoutType" to validate the phone number. Remember to provide the country code so the library can apply the appropriate format automatically.

<script src="/scripts/libphonenumber-js.min.js"></script>
<script>
  var libphonenumber = window['libphonenumber-js']
  alert(new libphonenumber.asYouType('US').input('213-373-4253'))
</script>

Do you have better solution? Please share it with us in the comments. Thank you!

Post a Comment

Previous Post Next Post