断电话号码验证

时间:2017-12-15 01:48:58

标签: jquery validation

我有一个电话号码验证脚本在多个站点上运行突然中断。功能正常,它只需要10个字符,剥离所有非数字字符(包括x,#,*,(,-),使用区号验证电话号码(为了空间,下面的片段只有5个)。但是,目前,电话字段允许所有字符和任意数量的字符。试着找出这里可能出错的地方。

验证脚本

jQuery.validator.addMethod("phone", function(value, element) {
    if(value.length > 10)
    {
        if(value.charAt(0) == 1) {
            value = value.substr(1)
        }
        var value = value.replace(/\D/ig,'');
        $(element).val(value)
    }
    var list = [201,202,203,204,205];
    var area = value.substring(0, 3);
    if(list.indexOf(parseInt(area)) == -1)
    {
        return false;
    }
    return value.length == 10
}, "Invalid Phone");


jQuery('#form form').validate({
    rules: {
        Email: {
            required: true,
            email: true
        },
        First_Name: {
            required: true,
            alpha: true
        },
        Last_Name: {
            required: true,
            alpha: true
        },
        Primary_Phone: {
            phone: true
        },
        City: {
            alpha: true
        }
    },
    messages: {
        required: "Required"
    }
});

电话字段

<input name="Primary_Phone" type="tel" class="phone form-control" placeholder="5555555555" required="">

1 个答案:

答案 0 :(得分:1)

对于给定的脚本,如果用户输入的字符数超过10个,则所有非数字字符都将被条带化。我想你想要排除所有非数字字符,无论用户输入多少字符?

jQuery.validator.addMethod("phone", function(value, element) {
    var value = value.replace(/\D/ig,'');
    $(element).val(value)
    if(value.length > 10)
    {
        if(value.charAt(0) == 1) {
            value = value.substr(1)
        }
    }
    var list = [201,202,203,204,205];
    var area = value.substring(0, 3);
    if(list.indexOf(parseInt(area)) == -1)
    {
        return false;
    }
    console.log(value);
    return value.length == 10
}, "Invalid Phone");

jQuery('form').validate({
    rules: {
        Primary_Phone: {
            phone: true
        },
    },
    messages: {
        required: "Required"
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<form>
  <input name="Primary_Phone" type="tel" class="phone form-control" placeholder="5555555555" required="">
</form>