jQuery Validation插件:如何强制使用某种电话号码格式### - ### - ####

时间:2013-03-18 16:59:57

标签: jquery jquery-validate

我在页面上有jQuery Validation插件。当有人在表单字段中键入电话号码时,我希望验证程序仅识别某种格式:

###-###-####

我在JavaScript中看到了这一点:

phone_number: {
    required: true,
    number: true 
},

我可以在那里添加一些内容来指定电话号码所需的格式吗?我找到了关于添加jQuery Mask plugin的内容,但是如果我可以避免它,我宁愿不添加页面权重。 (另外......当然必须存在某种方式来验证某种格式。)

4 个答案:

答案 0 :(得分:14)

如果你有点灵活,

@Sparky's suggestion是好的,但是如果你想要这种格式,你可以添加一个自定义规则:

$.validator.addMethod('customphone', function (value, element) {
    return this.optional(element) || /^\d{3}-\d{3}-\d{4}$/.test(value);
}, "Please enter a valid phone number");

$(document).ready(function () {
    $("#myform").validate({
        rules: {
            field1: 'customphone'
        }
    });
});

示例: http://jsfiddle.net/kqczf/16/

您可以轻松将其转换为自定义类规则。这样您就可以为要获得规则的每个输入添加一个类,并可能省略validate调用中的rules对象:

$(document).ready(function () {
    $("#myform").validate();
});

<input type="text" name="field1" id="field1" class="required customphone" />

示例: http://jsfiddle.net/kqczf/17/

答案 1 :(得分:6)

只需使用jQuery Validate plugin's additional-methods.js file中包含的phoneUS规则。

DEMO:http://jsfiddle.net/c9zy9/

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            phone_number: {
                required: true,
                phoneUS: true
            }
        }
    });

});

或者,您可以拔出additional-methods.js方法,而不是包含整个phoneUS文件。

DEMO:http://jsfiddle.net/dSz5j/

$(document).ready(function () {

    jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, "");
        return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
    }, "Please specify a valid phone number");

    $('#myform').validate({ // initialize the plugin
        rules: {
            phone_number: {
                required: true,
                phoneUS: true
            }
        }
    });

});

答案 2 :(得分:2)

查看jQuery Masked Input Plugin。它允许您使用以下内容屏蔽输入:

$("#phone_number").mask("999-999-9999");

答案 3 :(得分:0)

你应该尝试这个,它可以根据你的要求运作良好

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      phoneUS: true
    }
  }
});