Javascript phone number validation

后端 未结 7 804
感动是毒
感动是毒 2020-12-01 18:51

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

相关标签:
7条回答
  • 2020-12-01 19:07

    You could use Regular Expressions:

    function validatePhone(field, alerttext) {
        if (field.match(/^\d{10}/)) {
             return true;
        } 
        alert(alerttext);
        return false;
    }
    
    0 讨论(0)
  • 2020-12-01 19:09

    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.

    0 讨论(0)
  • 2020-12-01 19:12

    Add the pattern in which format you want directly in input tag.

    <input id="phone" name="phone" pattern="\d{10}" class="text" />
    
    0 讨论(0)
  • 2020-12-01 19:17
    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.

    0 讨论(0)
  • 2020-12-01 19:17

    Code to except only numbers braces and dashes

    function DoValidatePhone() {
        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);
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 19:19

    Fixed function:

    function validateForm(thisform) {
            if (validatePhone(thisform.phone,"Invalid phone number")==false) {
                thisform.phone.focus();
                return false;
            }
            return true;
    }
    
    0 讨论(0)
提交回复
热议问题