Validating phone numbers in JavaScript

By Faruque Ahamed Mollick

Here in this post, we are going to see how to validate phone number from a text type HTML input field. Phone number validation is often used in web. So it will be good if we see how to do it using JavaScript.

To validate phone number from text type input field we are going to use jQuery. We are going to check if the value of the phone input field is a valid phone number or not when the form is going to be submitted.

Detect arrow key press in JavaScript

Show live preview of HTML textarea with JavaScript

At the very first, let’s create our HTML form with one text input field:

<form id="myForm">
  <input type="text" name="phone" id="phone">
  <input type="submit" name="submit">
</form>

This is really so simple form as this will be used only as an example for learning. In the above code, we have set the id of the form as “myForm” and the id of the phone input field as “phone” which is going to be used in our jQuery code.

Now below is our jQuery code:

   $('#myForm').on('submit', function() {
      
      var phone = $('#phone').val();
      //alert(phone)
      if (isNaN(phone) || phone.length < 10 || phone.length > 10) {
        alert(phone+" please enter a valid phone number");
        return false;
      }
      else 
      {
        return true;
      }

    });

On submitting the form, the jQuery first checks if the phone input field has the value with number and length is between 10. The JavaScript isNaN method is used to check if the input data contains the only number. The isNaN method stands for Is Not A Number. from the name you can understand how it works.

Live word counter from HTML textarea in JavaScript

Now let’s test it on your browser. You will see if any of the characters in the phone field is not a number or is less than 10 in length or greater than 10 in length, the form will not be submitted. It will show the alert message for the invalid phone number and return false.

If the value of the phone input field contains numbers and equal to 10 in length, then you will see the form will be submitted.

Leave a Reply

Your email address will not be published. Required fields are marked *