代码之家  ›  专栏  ›  技术社区  ›  Federico klez Culloca

javascript电话号码验证

  •  11
  • Federico klez Culloca  · 技术社区  · 15 年前

    我需要用javascript验证一个电话号码。 要求如下:

    它们应该是10位数,没有逗号,没有 破折号,只是数字,而不是 前面1 +

    这是我到目前为止写的

    function validatePhone(field,alerttxt) {
        with (field) {
            if(value.length > 10) {
                alert(alerttext);
                return false;
            }
            for(i = 0; i < value.length; i++) {
                if(parseInt(value[i]) == NaN) {
                    alert(alerttxt);
                    return false;
                }
            }
            return true;
        }
    }
    function validateForm(thisform) {
            if (validatePhone(phone,"Invalid phone number")==false) {
                phone.focus();
                return false;
            }
    
        }
    }
      <form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
        <ol>
            <label for="phone">Your phone <span class="red"></span></label>
            <input id="phone" name="phone" class="text" />
          </li>
        </ol>
      </form>
    

    但是,很明显它不起作用。 我怎么能写 validatePhone() 功能让它工作?

    6 回复  |  直到 9 年前
        1
  •  29
  •   Erik    15 年前
    phone = phone.replace(/[^0-9]/g, '');
    if(phone.length != 10) { 
       alert("not 10 digits");
    } else {
      alert("yep, its 10 digits");
    } 
    

    这将根据您的要求进行验证和/或更正,删除所有非数字。

        2
  •  11
  •   Aaron Gray    11 年前

    谷歌 libphonenumber 对全球电话号码的验证和格式化非常有帮助。与使用regex相比,它更简单、更隐蔽、更健壮,它有javascript、ruby、python、c_、php和objective-c风格。

        3
  •  7
  •   arnep    11 年前

    可以使用正则表达式:

    function validatePhone(field, alerttext) {
        if (field.match(/^\d{10}/)) {
             return true;
        } 
        alert(alerttext);
        return false;
    }
    
        4
  •  1
  •   Peter Brooks    11 年前

    除数字外,代码为大括号和破折号

    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;
        }
    }
    
        5
  •  0
  •   antyrat Andy    15 年前

    固定功能:

    function validateForm(thisform) {
            if (validatePhone(thisform.phone,"Invalid phone number")==false) {
                thisform.phone.focus();
                return false;
            }
            return true;
    }
    
        6
  •  -1
  •   Narendrasingh Sisodia    9 年前
    function validate(phoneString){
    
        reg = /^([+|\d])+([\s|\d])+([\d])$/;
    
        return reg.test(phoneString);
    
    }