Skip to content Skip to sidebar Skip to footer

Javascript Phone Number Validation

I need to validate a phone number in javascript. The requirements are: they should be 10 digits, no comma, no dashes, just the numbers, and not the 1+ in front this is what I

Solution 1:

phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) { 
   alert("not 10 digits");
} else {
  alert("yep, its 10 digits");
} 

This will validate and/or correct based on your requirements, removing all non-digits.

Solution 2:

Google's libphonenumber is very helpful for validation and formatting of phone numbers all over the world. It is easier, less cryptic, and more robust than using a RegEx, and it comes in JavaScript, Ruby, Python, C#, PHP, and Objective-C flavors.

Solution 3:

You could use Regular Expressions:

functionvalidatePhone(field, alerttext) {
    if (field.match(/^\d{10}/)) {
         returntrue;
    } 
    alert(alerttext);
    returnfalse;
}

Solution 4:

Code to except only numbers braces and dashes

functionDoValidatePhone() {
    var frm = document.forms['editMemberForm'];                
    var stripped = frm.contact.value;
    var isGoodMatch = stripped.match(/^[0-9\s(-)]*$/);
    if (!isGoodMatch) {
        alert("The Emergency Contact number contains invalid characters." + stripped);
        returnfalse;
    }
}

Solution 5:

Fixed function:

functionvalidateForm(thisform) {
        if (validatePhone(thisform.phone,"Invalid phone number")==false) {
            thisform.phone.focus();
            returnfalse;
        }
        returntrue;
}

Post a Comment for "Javascript Phone Number Validation"