Table of Content
Enter components of form tel are utilized to allow the user to edit and enter a phone number. Contrary to input type=”email” and input type=”url”, the data is not automatically confirmed to a specific format before the form may fill, because formats for phone numbers change so much across the world.
Even though inputs of form tel are functionally identical to standard text inputs, they do serve useful functions; the most rapidly evident of them is that cellular browsers – particularly on mobile phones – might elect to present a personalized keypad optimized for entering telephone numbers.
Employing a particular input type for phone numbers also makes incorporating custom validation and handling of cell telephone numbers more suitable.
Why is it necessary to validate phone numbers in HTML forms?
The phone number is a significant point while supporting an HTML form. In this web page we’ve discussed how to confirm a telephone number (in various formats) with JavaScript:
Initially, we affirm that a telephone number of 10 digits without a comma, no spaces, no punctuation and also there’ll be no + sign before the amount. Just the validation will get rid of all non-digits and allow only telephone numbers with ten digits.
How to validate a phone number?
With a simple JavaScript code:
function phonenumber(inputtxt) { var phoneno = /^\d{10}$/; if((inputtxt.value.match(phoneno)) { return true; } else { alert("message"); return false; } }
If you want to use a + before the phone number, use the following code:
function phonenumber(inputtxt) { var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/; if((inputtxt.value.match(phoneno)) { return true; } else { alert("message"); return false; } }
How to validate a ten digit phone number?
Here’s what you need:
function phonenumber(inputtxt) { var phoneno = /^\d{10}$/; if(inputtxt.value.match(phoneno)) { return true; } else { alert("Not a valid Phone Number"); return false; } }
The code always depends on your validation needs. This small example can serve as a start to use phone validation in JavaScript in the right way.