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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15482532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:09:51  来源:igfitidea点击:

jQuery Validation plugin: How to force a certain phone number format ###-###-####

jqueryjquery-validate

提问by Sparky

I have jQuery Validation plugin on a page. When someone types the phone number into the form field, I want the validator to only recognize a certain format:

我在页面上有 jQuery 验证插件。当有人在表单字段中输入电话号码时,我希望验证器只能识别某种格式:

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

I see this in the JavaScript:

我在 JavaScript 中看到了这一点:

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

Can I add something there to specify the required format for the phone number? I found something about adding the jQuery Mask plugin, but if I can avoid it, I'd rather not add to the page weight. (Plus...surely there must exist some way to validate only a certain format.)

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

回答by Andrew Whitaker

@Sparky's suggestionis good if you are a little flexible, but just in case you want justthat format, you can add a custom rule:

如果您有点灵活,@Sparky 的建议很好,但以防万一您只需要这种格式,您可以添加自定义规则:

$.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'
        }
    });
});

Example:http://jsfiddle.net/kqczf/16/

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

You can easily make this into a custom class rule. This way you could just add a class to each input that you want to have the rule and possibly omit the rules object from the validatecall:

您可以轻松地将其变成自定义类规则。通过这种方式,您可以为每个想要拥有规则的输入添加一个类,并可能从validate调用中省略规则对象:

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

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

Example:http://jsfiddle.net/kqczf/17/

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

回答by Sparky

Simply use the phoneUSrule included in the jQuery Validate plugin's additional-methods.jsfile.

只需使用phoneUS包含在jQuery Validate 插件additional-methods.js文件中的规则。

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

演示:http: //jsfiddle.net/c9zy9/

$(document).ready(function () {

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

});

Alternatively, instead of including the entire additional-methods.jsfile, you can just pull out the phoneUSmethod.

或者,additional-methods.js您可以不包含整个文件,而只需提取该phoneUS方法。

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

演示: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
            }
        }
    });

});

回答by user1936123

Check out the jQuery Masked Input Plugin. It allows you to mask the input with something like this:

查看 jQuery屏蔽输入插件。它允许您使用以下内容屏蔽输入:

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

回答by SagarPPanchal

You should try this, and it works well as per your requirement

你应该试试这个,它可以根据你的要求很好地工作

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