Hello readers, in this blog we will discuss how to check a valid phone number in the form. Sometimes you need to add the validation for the phone number which requires a certain format.
We have to access the value which is in the form field and then by using a regular expression to validate the format.
If we need to validate a U.S.-based phone number by using (area + prefix + digits):
Syntax:-
// filter out anything but numbers to
// standardize input
var phone = document.forms[0].elements["intext"].value;
var re = /\D+/g;
var cleanphone = phone.replace(re,"");
// check length
if (cleanphone.length < 10) alert("bad phone");
When you need to validate the form field you can strip out the particular material first and then test what is necessary. Different formats are used to in phone numbers:-
(314) 555-1212
314-555-1212
314.555.1212
3145551212
When you need to validate the phone number you can do one thing just strip out anything that is not a number and then stat checking the length as shown in the example
You can reformat phone number into a standard format when you validate it, Usually, if you are going to save that number into the database, in that case, you have to add the smallest form possible for all numbers.
You may give three fields for the number to ensure that the data is correct or not and allow the format (3-3-4) for each character of the number. But it is a simple way if you give just one field for your users.
There are regular expression formulas for any number that work for validation in a various purpose.
Note:- Many Javascript framework and libraries give a simple validation function, In order to trigger the validation for proper working you have to do just give each input element a class name or some indicator for trigger the validation function.
0 Comment(s)