Zephyrnet Logo

Validate Phone Numbers in JavaScript with Regular Expressions

Date:

Introduction

Whether you realize it or not, data has become a crucial part of our day-to-day lives. From ordering food online to searching for cat food, we are constantly sending and receiving data. As developers of web applications, it is our responsibility to ensure that user inputs are in the specified format so that the database understands the data correctly, and the application remains robust.

Phone number validation is important because it ensures that data is saved in a consistent format throughout the database. For instance, users might need clarification on whether they should input the country code before their phone number. With proper validation in place, users can easily determine if it is required. Similarly, the user experience improves with a consistent format, as you know what to expect from users and can implement logic accordingly. It would be a poor experience for users if the code breaks at a later stage due to inconsistent data.

Regular expressions are powerful tools for pattern matching. They provide the flexibility to match patterns of various types, depending on your use case. Additionally, regular expressions are language-agnostic, making your validation logic more portable, as you can easily integrate the core validation. Working with regex in JavaScript is a straightforward task.

This article will help you understand how to use the power of regular expressions to validate phone numbers for your application. You will write a simple JavaScript function to validate phone numbers with country codes.

What Is a Regular Expression?

In simple terms, a regular expression matches a predefined pattern in a given string. It is widely used in programming languages and primarily employed for validating inputs of a specific format. Furthermore, regular expressions are commonly used for searching, splitting, and substituting specified patterns.

Let’s say you want to find an email address in a document. The email address could be any address, not a specific one. Writing a simple expression will help you find the pattern quickly since you already know the structure of an email address.

A regular expression uses special characters to denote different types of patterns. For example:

  • . (dot) is 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.

These are just a few. If you want to dive deeper and learn about more patterns, you can refer to this document from Microsoft.

Let’s 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. From the list above, we know that $ is used for matching the end of the line.

Combining this information, we get a regular expression like this:

/^d{5}$/

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

Regular expression to match five-digit zip code

Regular Expression to Match Five-Digit Zip Code

Now that we have a basic understanding of regular expressions and their general construction, it’s a good time to explore how these expressions can be implemented in a JavaScript function.

JavaScript Regular Expressions

JavaScript is the most popular programming language among developers. Since 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. This object can be utilized in two ways:

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

Literal notation can be used as simply as this:

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

On the other hand, with constructor notation, you’ll need to use the RegExp constructor to create an instance of it. Here’s how it looks:

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

You can read more about the RegExp object from the official MDN docs. Now, let’s explore the importance of phone number validation and the various components of a phone number.

Phone Number Validation and Components

Validating phone numbers on the client side is crucial when saving phone numbers in your database. Without proper validation, your code might exhibit unexpected behaviors.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

For example, suppose 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. This is just one hypothetical scenario. Other issues can even crash your application. It is crucial to properly handle your data in the frontend, ensuring that you save clean and consistent data across your database.

Generally, a phone number consists 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.

The article you’re currently editing is titled “Validate Phone Numbers in JavaScript with Regular Expressions”. The chunk of text to edit:

  • 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. This part of the number usually ensures that each phone number within a country, area, and prefix is unique.

Excluding the country code, combining the remaining parts results in a ten-digit phone number where the area code and the telephone prefix are three digits each, and the line number is four digits.

Let’s now move into writing a JavaScript function that validates a phone number based on these criteria using regular expressions.

Create a RegEx for Phone Number Validation

We have already understood the basic structure of a phone number. We have also learned about regular expressions and how they can be used in JavaScript. In this section, we will write a simple JavaScript function that validates phone numbers of the given format:

COUNTRY_CODE-AREA_CODE-TELEPHONE_PREFIX-LINE_NUMBER

For example, a valid phone number for our function will be like this +123-456-789-1234, but not +012-123-456-7890 or +12-123-456-789, as these phone numbers do not follow the rules of phone numbers we discussed earlier.

Now, let’s jump into writing the regular expression. First, let’s check if the country code is 1 to 3 digits long and doesn’t start with a zero.

To indicate the start of the regular expression, use a caret (^), then validate that a plus exists at the start. For this purpose, let’s use +, which will match that the plus exists at the start. Now, to ensure that the country code’s digits are between one to three digits and the first digit is not zero, we can write something like this: [1-9]{1}[0-9]{0,2}. Here, [1-9]{1} specifies that any digit from 1 to 9 can exist exactly once, and similarly, [0-9]{0,2} indicates that any digit from 0 to 9 can exist zero to two times.

For the separator, we can add a - (hyphen) between the sections of the number. One - can be added after the country code validation. So, at this point, the regex looks like this:

^+[1-9]{1}[0-9]{0,2}-$

The $ at the end specifies the end of the line. Now, for the area code, this will be quite similar. An area code cannot start with a zero or a one. So, the first part will be [2-9]{1}. This matches that the first number is between 2 and 9. This matching occurs one time. Then, for the rest of the code, we can write [0-9]{2}. This will ensure that there are exactly two digits after the first one, and for each digit, the range is between 0 and 9. Again, add the hyphen separator at the end.

Now, the complete regexp will look like this:

^+[1-9]{1}[0-9]{0,2}-[2-9]{1}[0-9]{2}-$
|----Country Code---|-|---Area Code--|-|

Let’s again use the same pattern for checking the telephone prefix. Let’s assume that the telephone prefix also cannot start with a zero or a one. So, adding [2-9]{1}[0-9]{2} and a hyphen again will make the expression like this:

^+[1-9]{1}[0-9]{0,2}-[2-9]{1}[0-9]{2}-[2-9]{1}[0-9]{2}-$
|----Country Code---|-|---Area Code--|-|--Tel Prefix--|-|

The only part remaining now is the line number, which can be any digit with a length of exactly four. This is simpler than the other ones. The expression is [0-9]{4}.

The complete expression is as follows:

^+[1-9]{1}[0-9]{0,2}-[2-9]{1}[0-9]{2}-[2-9]{1}[0-9]{2}-[0-9]{4}$
|----Country Code---|-|---Area Code--|-|--Tel Prefix--|-|-Line-|

You must have noticed the frequent use of curly braces. They are used to match the instances provided inside the brace. If it’s a specific digit, like {1}, it’ll match the preceding pattern exactly one time. However, if it’s a range, like {0, 2}, it defines the minimum and maximum number of matches. So, in the case of {0, 2}, it’ll match the pattern for a minimum of zero times and a maximum of two times.

The pattern is ready. We can now write a simple JavaScript function to check if a phone number is valid using the regular expression. Here’s the function:

function validatePhoneNumber(phoneNumber) { const pattern = new RegExp("^+[1-9]{1}[0-9]{0,2}-[2-9]{1}[0-9]{2}-[2-9]{1}[0-9]{2}-[0-9]{4}$"); if (pattern.test(phoneNumber)) { console.log("Phone number is valid"); return true; } else { console.log("Phone number is not valid"); return false; }
} validatePhoneNumber("+123-456-789-1234"); validatePhoneNumber("+0-123-456-7890"); validatePhoneNumber("+12-012-123-1234"); 

The function is quite straightforward. It takes a phone number as input. The regular expression pattern is stored inside a variable called pattern. The pattern is instantiated using the RegExp constructor and passing the expression as a parameter to the constructor. Then, we test the phone number using the test method available in the object. Using an if-else statement, we check if the phone number passes the test. If it does, we return true and send a console message stating that the Phone number is valid. Otherwise, it returns false and displays a console message indicating that the phone number is not valid.

With this, we are good to go. Now, you can test your phone numbers to see if they are valid.

Summary

This article aimed to provide a brief overview of regular expressions, their uses, and how they can be applied to validate phone numbers. We also discussed the various components of a phone number and how each component can be tested.

With a basic understanding of regular expressions, you can now explore additional patterns. You can also use tools like Regex101 for validating your expressions online.

spot_img

Latest Intelligence

spot_img

Chat with us

Hi there! How can I help you?