Phone number validation in JavaScript

You are currently viewing Phone number validation in JavaScript
Validate ohone number using javascript

Test Cases :

  • allow to enter only number in html input field 
  • allow to enter 0-9 ,+ and space
  • add max length to input field
  • using charCode to validate input 

In this article we will learn phone number validation in html using JavaScript, when you create any form you have to add validation to it like – phone number validation or email validation. Today we will discuss how to restrict input field to enter specific set of character or numbers.

In html5 we can use input filed with type=’number’ which will allow you add number , but the problem with that is it also except character like ( e,- + ) etc. We know that we can have + in phone number but input=’number’ allows to add + more that one time which is not acceptable sometimes.

Now let’s see how to write a JavaScript code to handle phone number validation, first we need to create html input field of type text and on onkeypress we will call JS method which will check for the input based on key charCode. 

phone number validation in html using javascript

				
					<body>
    <label for="phone">Phone</label>
    <input id="" maxlength="14" type="text" onkeypress='return allowToEnterPhoneNumber(event)'>

    <script>
        function allowToEnterPhoneNumber(e){
                var charCode;
                document.all ? charCode = e.keyCode : charCode = e.which;
                let numberEntered = e.target.value;
                var plusExist = numberEntered.includes('+');
                let isInputAllowed = null;
                if(plusExist)
                    isInputAllowed = ((charCode > 47 && charCode <= 57) || (charCode==32) );
                else
                    isInputAllowed = ((charCode > 47 && charCode <= 57) || charCode == 43 || (charCode==32));
                return isInputAllowed
            }
    </script>
</body>
				
			

The about code will allow you to enter number with for format like 

  • +9112345 12345
  • 12345 68800
  • +0012345644

Similarly if you want to allow some other character to the input filed then you have add or remove charCode according to your requirement.

We have used maxlength attribute to the input field to hold the max-length. Here you can notice that we have not used regex to validate phone number but this can done by using regex as well.

Leave a Reply