JavaScript

Working with Phone Numbers in JavaScript code

One of the major problems that developers face in their early development is how to take data from a user and then validate that data. If you are taking an input like a name or registration number from a user then you can easily validate that data, however, it becomes a little complex when you are taking input as a phone number.

In this post, we will go through how to take a phone number as input from a user and then validate it according to our needs in this post using the HTML5 input tag with tel type and then using a simple input tag of HTML and validating it ourselves using JavaScript.

Using HTML5 input tag with tel type

We can use the HTML5 input tag to take input from the user and we can give the type of tel in the input tag to tell the browser that this input box should take a phone number. The HTML5 input tel type has some advantages one being that we can set the required attribute in the input tag telling the browser that the user cannot proceed without entering the phone number and the other is that we can set a pattern attribute. Let us demonstrate the input tag in HTML:

<input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>

In the above code we can see that we have given a regular expression as a pattern to the input tag and hence using this will validate the phone number. Let’s view a proper HTML program:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

</head>

<body>

  <form id="myform" action="javascript:void(0)">

    <label for="myform_phone">Example: 123-456-7890</label>

    <input type="tel" id="myform_phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="Enter Phone Number"/>

    <button type="submit">Submit</button>

  </form>

</body>

</html>

In the above code, we initialized the label tag which shows an example of the phone number that is accepted by the below input tag where we have defined a pattern. Now the input tag itself will be responsible for validating the input taken from the user. After this, we defined a button and gave it the type of button. Whenever a user will click on the submit button it will generate a response based on the form tag action. Some of the examples are below:

If we click on the submit button leaving the phone number input box blank:

If we give a wrong pattern and click on the submit button we will see the following warning:

Using JavaScript to validate Phone Number

We can also validate the phone number using JavaScript. For this first we will create an input tag and a button in HTML in the following manner:

<!DOCTYPE html>

<html lang="en">

<head>

  <title>Document</title>

</head>

<body>

  <label for="myPhone">Example: 123-456-7890</label>

  <input type="tel" id="myPhone" placeholder="Enter Phone Number">

  <button onclick="handleClick()">Submit</button>


  <script src="code.js"></script>

</body>

</html>

We used the onclick event on the button element which means whenever a user clicks on the submit button, the handleClick() function will start executing. This handleClick() function will be initialized in a separate file code.js which we referenced using the script tag seen in the above code.

Let us now work on the JavaScript part:

// function to handle click on submit button
const handleClick=()=>{

    // getting the reference of myPhone input

    var input = document.getElementById("myPhone").value;

    // format for the phone number

    var format = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/;


    // conditional statements

    if(input===''){

        alert("Please Enter Phone Number")

    }

    else if(input.match(format)){

        alert("Phone Number: "+ input);

    }

    else{

        alert("Type using correct format");

    }

}

In the above code, first, we initialized the handleClick() function and then we reference the value of the input tag. After that, we define the format of the phone number that we want using regular expressions. An accepted phone number example, in this case, would be 123-456-7890. Next, we use the conditional statements and we check that if the input is empty then alert Please Enter Phone Number else if the input matches the format then alert that number otherwise alert that the number the user has types is in the wrong format. Let us view the output one by one:

First, we will click on the submit button while leaving the input box blank:

Next, we will type a wrong format number, then we will see the following output:

In the end, let us go for the correct format and see the output:

Conclusion

Validating phone numbers in JavaScript can become a headache for a new developer. There are two methods that we can use to validate phone numbers. First, to take input from a user with the help of an HTML input tag. Next to validate the phone number we give the input tag the type of tel and a pattern to which it should validate. The second method is making a custom JavaScript program that will validate your phone number according to a given format given as a regular expression.

In this post, we learned how to take a phone number as an input from a user and then we validated that phone number using two methods; HTML5 input tag with tel type and custom JavaScript logic.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.