js validate phone number

How to Validate Phone Numbers with JavaScript

Validating phone numbers is an essential part of web development. In this article, we will discuss how to validate phone numbers using JavaScript.

Method 1: Using Regular Expressions

Regular expressions are a powerful tool for pattern matching. We can use regular expressions to validate phone numbers in JavaScript. Here is an example:


function validatePhoneNumber(phoneNumber) {
  var regex = /^\d{10}$/;
  return regex.test(phoneNumber);
}

This function takes a phone number as input and returns true if the phone number is valid. The regular expression /^\d{10}$/ matches a string that contains exactly 10 digits.

Method 2: Using the HTML5 Pattern Attribute

The HTML5 pattern attribute allows us to validate input fields using regular expressions. We can use this attribute to validate phone numbers in HTML forms. Here is an example:


<input type="text" name="phoneNumber" pattern="^\d{10}$">

This input field will only accept input that matches the regular expression /^\d{10}$/.

Method 3: Using a JavaScript Library

There are many JavaScript libraries available that can help us validate phone numbers. One popular library is libphonenumber. This library is developed by Google and provides comprehensive phone number validation and formatting.

To use this library, we need to include the script file in our HTML page:


<script src="https://rawgit.com/googlei18n/libphonenumber/master/dist/libphonenumber.js"></script>

Here is an example of how to use the library:


function validatePhoneNumber(phoneNumber) {
  var phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
  var number;
  try {
    number = phoneUtil.parse(phoneNumber, "US");
  } catch (e) {
    return false;
  }
  return phoneUtil.isValidNumber(number);
}

This function uses the libphonenumber library to validate the phone number. The library is also used to parse the phone number and determine its country code.

  • Method 1: Using Regular Expressions
  • Method 2: Using the HTML5 Pattern Attribute
  • Method 3: Using a JavaScript Library

These are three different ways to validate phone numbers using JavaScript. Choose the method that best fits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe