JavaScript Regular Expression for Phone Number Verification

JavaScript Regular Expression for Phone Number Verification

The ability to collect a phone number and quickly verify its existence and validity has great value for businesses, whether to ensure a global reach for website sign-ups or to prevent account creation by bots and protect a real user’s account credentials. 

The problem is getting people to enter their phone numbers in the correct format. That being said, the solution should be one that works with multiple countries and carriers. A typical solution is to use regular expressions to make sure the value looks like a valid phone number.

Differences in Phone Numbers

A valid phone number can take on a variety of forms depending on the region. There are universal rules, such as limiting the length of digits or the number containing only numerical values (with slight deviations). Still, in some cases, a telephone number can take on a format using parentheses, plus signs, spaces, and dashes and have different code systems.

The goal for phone number validation is to be able to check whether, for example, +1-541-754-3010 or 19-49-89-636-48018 are correct. 

International Dialing Code System

For some operations, like collecting numbers for manual processing, you might not need the mechanisms for international contact verification;however, it’s often important to maintain flexibility for international dialing codes. This is especially useful if you want to introduce some level of automation. 

Figuring out a valid country prefix presents some challenges as well. For one, 7, 55, 351, and 1809 are equally valid codes but even then, the process isn’t straightforward. The prefix +1 works for both the United States and Canada, whereas +34 works for Spain and the Canary Islands. 

Additionally, the conventions for dialing telephone numbers vary depending on where you’re calling from. For instance, in the United Kingdom, there are geographic numbers officially approved by the Office of Communication, such as 020 for London or 01865 for Oxford. It would make a local number look like 020 7946 0636. 

But an international number format normally starts with +44, so it would be +44 20 7946 0636. Also, an international phone prefix could be 00 instead of “+” so 0044 20 7946 0636 would be another expression of the same number.

If you’re dialing the UK from the US, you will need to enter the digits 011, which signals that you are making a call outside of the United States. In this case, the number would be 011 0044 20 7946 0636.

Changes in Phone Numbers

There are internal and external factors that affect code systems for different countries. In the 20th century, nine countries ceased to exist. Since telephone numbers are managed by the national telecommunications authorities, those dialing systems also no longer exist.

Countries constitute proposing and implementing new classification systems – premium-rate, local-rate, toll-free, etc. Once telephone providers reach the limits for premiums, they can simply announce a new code.

Conventions can also drastically change over time. South Korean phone numbers can be as short as seven digits or as long as 11 digits, but that hasn’t always been the case. In addition to landline and mobile phone numbers, authorities gradually introduced new versions – national service, business, and alternative numbers. 

Lastly, you have to account for the massive growth of mobile communications. The number of people relying on mobile phones is rapidly increasing and the pool of available phone numbers is likely to have further implications on international phone conventions. 

International Phone Number Standard

To simplify telecommunication numbering plans, there is an internationally-recognized phone number format. It is called ITU-T E.164 or simply E.164. It defines the structure and functionality for the following four principal categories of numbers:

  • Geographic area
  • Group of countries 
  • Network
  • Global Subscriber Number (GSN)

The E.164 standard eliminates the formatting ambiguity through the following rules:

  • It imposes a maximum length of 15 digits per telephone number with the shortest ones currently being seven digits.
  • It should include a country calling code or country dial-in code, such as +1 and +44.
  • The next element is the national destination code (NDC), such as 7911.
  • Lastly, the sequence must include a subscriber number (SN), such as 651780.

In total, the example phone number according to E.164 is +447911651780. 

The goal of this regulation is to have valid telephone numbers represented consistently. Callers should use a plus sign (+) prefix in place of any international call prefix. In terms of numerical digit separations, it only accepts spaces without dashes. While the incorporation of the tilde (~) is technically acceptable for indicating an additional dial tone, it’s not included in the regular expression because it is so infrequently used.

Collection of Information

The process of collecting user input should minimize the possibility of the wrong phone number format. A validation error can cause users to get frustrated and leave the website, but there are effective practices that help users enter phone numbers in valid formats.

Providing Hints

As a way to simplify and improve user experience, there are a couple of ways to help users enter the information correctly the first time. This can be done through design elements that will provide tips for the expected input. 

The first one is using text prompts under the input field or those that appear when the user starts entering information. The prompt can say: “Enter the number in the international format without the + symbol, for example (899) 999999.” 

The second option is to use the placeholder HTML attribute. The placeholder attribute will help show the expected input format without using additional tags. For example, it can be a sample number or a short explanation of it:

<form action="/action_page.php">
  <label for="phone">Enter a phone number:</label><br><br>
  <input type="tel" id="phone" name="phone" placeholder="123-45-678"
  pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"><br><br>
  <small>Format: 123-45-678</small><br><br>
  <input type="submit">
</form> 

“tel” Input Type

The "tel" input type is designed to help web developers create input fields for phone numbers and is used as follows:

<label for = "phone"> Enter your phone number: </label>

<input type = "tel" id = "phone" name = "phone" pattern = "[0-9] {3} - [0-9] {2} - [0-9] {3}">

However, there is not much support for this attribute by plugins. Most browsers will process your input field as a regular "text" input, therefore, it’s not recommended to rely exclusively on the “tel” attribute. 

Plugins

JavaScript is known for its wide assortment of plugins. They allow you to execute everyday tasks efficiently without having to write the same things over and over again. For real-time validation of telephone numbers, there are many plugins that allow you to quickly implement the following:

  • Attach a country dropdown that allows users to easily select their international country code.
  • Detect location using the IP address of the visitor and provide them with the input placeholder based on the expected number format for their country.
  • Quickly convert the user input into an internationally-recognized standard phone number format.
  • Validate the number by providing specific controls, including error types.
  • Show country flag icons and other out-of-box modern design elements.

Most plugins are also compatible with all varieties of JavaScript frameworks and platforms. This means real plug-and-play installation and easy access to many customization options.

Libphonenumber Library

One of the most popular plugins for phone number formatting and parsing is the Libphonenumber library released by Google. It was initially created to be used in Android operating systems. 

It was ported by Google to be used in Java, C++, and JavaScript systems, but also has been rewritten by community members. Below, we will be talking about the Libphonenumber-js version of that library, which provides better optimization and more features compared to Google's auto-generated JavaScript port.

Basic Concepts 

The library can format, parse, and validate international telephone numbers using the following scripts: 

  • getNumberType – Determines the type of a valid phone number. If possible, categorizes mobile, fixed-rate, toll-free, premium rate, VoIP, or personal numbers.
  • isNumberMatch – Uses confidence intervals to determine if two numbers are identical.
    getExampleNumber/getExampleNumberByType – Shows example numbers for different locations. You can also sort them by specific types.
  • isPossibleNumber – Determines whether the number could be valid based on its length. 
  • isValidNumber – Validating numbers by different lengths, country codes, and number prefix.
  • AsYouTypeFormatter – Formats phone numbers as they are entered.
  • findNumbers – Finds numeric values from non-numeric characters. 
  • PhoneNumberOfflineGeocoder – Carries out international phone number geocoding.

Setup 

The easiest way to install Libphonenumber is by using a JS package manager:

via npm

$ npm install libphonenumber-js --save

via yarn

$ yarn add libphonenumber-js

If you're not using a bundler, then use a stand-alone version from a CDN. The plugin does not require any setup and can be used immediately after installation.

Coding

The best thing about the library is its ability to automatically parse and format phone numbers in any given input. You can start even with mixed type plain text:

import { findPhoneNumbersInText } from 'libphonenumber-js'

findPhoneNumbersInText(`

  For tech support call +7 (800) 555-35-35 internationally

  or reach a local US branch at (213) 373-4253 ext. 1234.

`, 'US')

// Outputs:
//
// [{
//   number: PhoneNumber {
//     country: 'RU',
//     countryCallingCode: '7',
//     number: '+78005553535',
//     nationalNumber: '8005553535'
//   },
//   startsAt : 22,
//   endsAt   : 40
// }, {
//   number: PhoneNumber {
//     country: 'US',
//     countryCallingCode: '1',
//     number: '+12133734253',
//     nationalNumber: '2133734253',
//     ext: '1234'
//   },
//   startsAt : 86,
//   endsAt   : 110
// }]

The library gives you the ability to quickly transform a phone number to any common web standard:

import { parsePhoneNumberFromString } from 'libphonenumber-js'

const phoneNumber = parsePhoneNumberFromString('+12133734253')

phoneNumber.formatInternational() === '+1 213 373 4253'

phoneNumber.formatNational() === '(213) 373-4253'

phoneNumber.getURI() === 'tel:+12133734253'

 

Or just make improvements to the user input:

import { AsYouType } from 'libphonenumber-js'

new AsYouType().input('+12133734')

// Outputs: '+1 213 373 4'

new AsYouType('US').input('2133734')

// Outputs: '(213) 373-4'

 

As expected, the library has a couple of core validation methods like isPossible() and isValid(). They offer a handy use of regular expressions that check whether the phone number is entered correctly.

There is also a React adaptation of that library with front-end components such as country flags included.

Validating a Number

We’ll assign a regular expression to check and validate a phone number:
/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/

To get a better understanding of what it entails, here is a breakdown of all the elements.

  • /^\(?: One of the optional forms of the number may start with an open parenthesis.
  • (\d{3}): Then it must include three numeric digits. If there is no parenthesis, the number must start with these digits, for example – (541 or 541.
  • \)?: This provides an option to include a close parenthesis.
  • [- ]?: The string may optionally contain a hyphen either after the parenthesis or following the first three digits.
  • (\d{3}): Then the number must contain another three digits. Depending on your previous options, it can look like (541)-753, 541-753 or 541753.
  • [- ]?: Once again, you can include an optional hyphen in the end – (541)-753-, 541-753- or 541753-.
  • (\d{4})$/: Lastly, the sequence must end with a four-digit sequence. It can look something like (541)-753-6010, 541-753-6010, 541753-6010, or 541753-6010.

To sum up, we’ve looked at all sorts of complexities and subtleties that are associated with the collection, validation, and display of phone numbers. Keep in mind differences in international formats unless you’re planning to hold operations in one country. 

Remember that any verification system is designed to help the user enter their real phone number correctly. Make sure that your form accepts all types of valid phone numbers in your country and other expected countries, and be sure to account for atypical cases and various input options. 

Your goal is to establish fairly flexible rules that will not force a person to rewrite their number multiple times but will successfully filter out fraudulent numbers.

 

 

Tags:javascript
B6A24216-9891-45D1-9D1D-E7359CEB8282 Created with sketchtool.

Comments(0)

Add your comment

Please complete this field.

Recommended

Sign up for a free Voximplant developer account or talk to our experts
SIGN UP