Using Regular Expressions to Verify Phone Numbers in JavaScript

In today’s world, data plays a crucial role in our daily lives. From online food ordering to searching for pet food, we are constantly transmitting and receiving data. As web application developers, it is our responsibility to ensure that user inputs are in the specified format, so that the database can understand the data accurately and the application remains strong. Phone number validation is essential to maintain consistency of data format in the database, as users may require clarification on whether they should input the country code before their phone number. By implementing proper validation, users can easily determine if it is required. Moreover, consistent data format results in improved user experience as the code is less likely to break due to inconsistent data. Regular expressions are powerful tools for pattern matching that allow you to match patterns of various types depending on your use case. Additionally, regular expressions are easily portable across different platforms, making them useful as core validation tools. Working with regular expressions in JavaScript is a simple task and this article aims to help you to understand how to use them to validate phone numbers with country codes. But first, let’s understand the basics of what a regular expression actually is.

A regular expression is simply a predefined pattern that matches a given string. It is frequently used in programming languages to validate inputs of a specific format, as well as for searching, splitting, and substituting specified patterns. For instance, if you want to find an email address in a document, a simple expression can be used to find the pattern quickly since you already know the structure of an email address.

Regular expressions use special characters to denote different types of patterns. They include:

– .(dot): a special character that can match any character
– *(asterisk): matches the preceding character 0 or more times
– +(plus): matches the preceding character one or more times
– ?(question mark): makes the preceding character optional
– [abc]: matches any of the characters a, b, or c
– (abc): groups characters together
– ^(caret): matches the start of the line
– $(dollar): matches the end of the line

There are more patterns that you can learn about by referring to this document from Microsoft.

Let’s take a look at an example to better understand how regular expressions work. Suppose we want to build a regular expression that checks if a given set of numbers is a five-digit zip code. To begin writing the expression, we’ll use the ^(caret) sign, as it matches the start of the line. In a regular expression, \d matches any digit, and a number inside curly braces ({}) matches the preceding element exactly the number of times given inside the braces. We know that $ is used for matching the end of the line. Combining these elements, we can create a regular expression like this: /^\d{5}$/

Now, let’s examine the graphic below to better understand this expression.

[Graphic showing a regular expression to match five-digit zip code]

Now that we have a basic understanding of regular expressions and how they work, let’s explore how they can be applied in JavaScript. JavaScript is the most popular programming language among developers, and as almost all web applications require JavaScript, it is crucial to understand how regular expressions can be used in this language. In JavaScript, the RegExp object is used for pattern matching and can be utilized in two ways:

– Using literal notation, where a pattern is formatted between two forward slashes; or
– Using constructor notation, where either a string or a RegExp object is passed.

Literal notation is as simple as this:

const expr = /^\d{5}$/i;

With constructor notation, you’ll need to use the RegExp constructor to create an instance of it:

const expr = new RegExp(/^\d{5}$/,”i”);

Read more about the RegExp object from the official MDN docs.

Now let’s explore the importance of phone number validation and its various components. Validating phone numbers on the client side is crucial when saving phone numbers in your database, as improper validation could cause your code to act unexpectedly. For example, imagine that you are using a service that requires the country code along with the phone number, but your users are not including them due to a lack of validation. Now, you only have the number without the country code, and a service that sends SMS text messages might fail because of this. It is crucial to properly handle your data in the frontend so that you can save clean and consistent data across your database.

In general, a phone number is made up of four parts:

– Country code: The first 1 to 3 digits (depending on the country) define the country of the phone number. This code allows the call to be routed to the correct country. A country code cannot start with a 0.
– Area code: Also known as the city or dialing code, this part of the number helps route the call to the correct geographical area within the country. In some countries, like the United States, area codes can also indicate a specific set of phone numbers for a particular service. Additionally, in North America, an area code cannot start with a 0 or a 1.
– Telephone prefix: This sequence of numbers is assigned to a specific central office or telephone exchange by the telephone company, further narrowing down the specific geographical area or neighborhood.
– Line number: This is the unique number assigned to the specific phone line for a household or business within the prefix area.

Excluding the country code, when you combine the remaining parts, you obtain a ten-digit phone number where the area code and the telephone prefix are made up of three digits each, and the line number is four digits. We can now use regular expressions to validate phone numbers based on these criteria.

Let’s write a simple JavaScript function that validates phone numbers in the format:


For example, a valid phone number for our function will be:


But not:




as these phone numbers do not follow the rules of phone numbers we discussed earlier.

To write the regular expression, we’ll first check if the country code is 1 to 3 digits long and doesn’t start with a zero. We’ll use a caret (^) to indicate the start of the regular expression, then validate that a plus exists at the start by using \+. Next, we’ll ensure that the country code’s digits are between one to three digits and the first digit is not zero by writing:


Here, [1-9]{1} specifies that any digit from 1 to 9 can exist exactly once, and [0-9]{0,2} indicates that any digit from 0 to 9 can exist zero to two times. We can add a hyphen (-) between the sections of the number as the separator. So the regex looks like this:


The $ at the end specifies the end of the line.

Now, for the area code, we can use a similar approach. We’ll first check that it is three digits long, and that the first two digits fall within the range of 0 to 9 and the third digit falls within the range of 2 to 9. Here’s what the regular expression looks like:


Now, let’s move on to the telephone prefix. To validate the telephone prefix, we’ll use a similar approach as we used for the area code. The regular expression checks that the prefix is three digits long, and the first digit falls within the range of 0 to 9 and the second and third digits fall within the range of 2 to 9. Here’s what the regular expression looks like:


Finally, let’s validate the line number. It should be four digits long and consist of digits between 0 and 9. Here’s what the final regular expression looks like:


Now that you know the pattern, you can create a simple JavaScript function that uses the pattern to validate phone numbers.

In summary, regular expressions are powerful tools for pattern matching, and they can be used in JavaScript for many purposes, including validating phone numbers. Proper validation of phone numbers on the client side ensures that your code acts as it should, and it prevents unexpected behaviors from occurring.

Source link

Leave a Reply