How to validate phone number in JavaScript

 
Regular expressions are a right way to validate text fields such as phone numbers, names, addresses, age, date and other input information. You can use them to constrain input, apply formatting rules, and check lengths.

A regular expression can easily check whether a user entered something that looks like a valid phone number.
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods.

In this article we will discuss about regular expression for validating Phone number in various format.

In the following example user enters a phone number. When the user presses Enter, than javaScript checks that phone number is valid or not. If the number is valid then alert message will be displayed as ‘Phone number is valid’. If the number is invalid, alert message will be displayed as ‘Phone number is not valid.

This javaScript code determine whether a user entered phone number in a common format that includes 0999999999, 099-999-999, (099)-999-9999, (099)9999999, 099 999 9999, 099 999-9999, (099) 999-9999, 099.999.9999 and all related combinations

For this we use this regular expression:
/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/

<html>  
  <head>  
      <script type="text/javascript">  
      var reg = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
      function PhoneValidation(phoneNumber)
      {  
        var OK = reg.exec(phoneNumber.value);  
        if (!OK)  
          window.alert("phone number isn't  valid");  
        else  
          window.alert("phone number is  valid");  
      }  
    </script>  
  </head>  
 
  <body>  
    <p>Enter your phone number and then press Enter.</p>  
    <form action="">  
      <input name="txtPhone" onchange="PhoneValidation(this);">  
    </form>  
  </body>  
</html>

similarly if we want to validate phone number like 999-999-9999 format then you can use /\d{3}-\d{3}-\d{4}/ regular expression.
 

One thought on “How to validate phone number in JavaScript”

  1. this site is very helpful.
    i’m wondering, given a phone number like this: “+1234567890″; is there a mathematical way to determine the country and area codes? — without looking at the code tables.
    what if there exist country codes “1″ , 12″ and “123″ ? how do we figure this out?
    Thanks.

Comments are closed.