jQuery Validation插件:如何强制使用某种电话号码格式###-###-#### [英] jQuery Validation plugin: How to force a certain phone number format ###-###-####
问题描述
我在页面上有jQuery Validation插件.当有人在表单字段中输入电话号码时,我希望验证器仅识别某种格式:
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:
###-###-####
我在JavaScript中看到了这一点:
I see this in the JavaScript:
phone_number: {
required: true,
number: true
},
我可以在此处添加一些内容以指定电话号码所需的格式吗?我发现了有关添加 jQuery Mask插件的一些信息,但是如果我可以避免这种情况,我宁愿不增加页面重量. (此外...当然,必须存在某种只验证某种格式的方法.)
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.)
推荐答案
@Sparky的建议如果您是不太灵活,但是如果您只想 这种格式,则可以添加自定义规则:
@Sparky's suggestion is good if you are a little flexible, but just in case you want just that format, you can add a custom rule:
$.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
调用中省略规则对象:
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 validate
call:
$(document).ready(function () {
$("#myform").validate();
});
<input type="text" name="field1" id="field1" class="required customphone" />
示例: http://jsfiddle.net/kqczf/17/
这篇关于jQuery Validation插件:如何强制使用某种电话号码格式###-###-####的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!