如何将自定义但非必需的方法添加到jQuery Validation插件? [英] How to add custom, but not-required, method to jQuery Validation plugin?

查看:69
本文介绍了如何将自定义但非必需的方法添加到jQuery Validation插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为jQuery Validation插件添加自定义方法,以检查有效的电话号码.但是,我希望此字段为可选字段,而不是必需字段.出于某种原因,当我添加以下代码时,它也会使字段具有"phone"类的要求.有什么想法我做错了吗?

I am adding in a custom method for the jQuery Validation plugin to check for a valid phone number. However, I want this field to be optional, and not required. For some reason, when I add the following code in, it is making fields with the class "phone" required too. Any ideas what I'm doing wrong?

$.validator.addMethod("phone", function(ph, element) {
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
});

$('#custom').validate({
    errorPlacement: function(error, element) {
        return true;
    }
}); 

<input type="text" class="phone" name="phone_1" id="phone_1">

推荐答案

您将要更新您的方法,以便在电话字段为空时返回true. 像这样:

You'll want to update your method so it returns true if the phone field is empty. Something like:

$.validator.addMethod("phone", function(ph, element) {
    if(ph=='') return true;
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
});

它将在所有电话字段上运行该方法,因此,除非它们实际包含内容,否则您可以通过它们未经测试地传递.

It's going to run the method on all of the phone fields, so this way you allow them to pass on untested unless they actually contain content.

这篇关于如何将自定义但非必需的方法添加到jQuery Validation插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆