jQuery验证插件:“验证"复选框 [英] jQuery Validation plugin: validate check box

查看:57
本文介绍了jQuery验证插件:“验证"复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery Validation插件来验证复选框,因为它没有默认选项,应该选中一个,最多可以选中两个复选框,这就是标准.我没有收到任何错误,也没有验证.我像下面这样扩展它,

I am using jQuery Validation plugin to validate check box since it does not have default option, One should be selected and max two check boxes can be selected, these is the criteria. I am not getting any error and it is not validating. I am extending it like below,

  <input type="checkbox" name="test[]" />x
   <input type="checkbox" name="test[]"  />y
   <input type="checkbox" name="test[]" />z
     $("#formid").validate({
  rules: {
    test[]: { 

            required: function(elem)
            {
                return $("input.select:checked").length > 0;
            }

          },
messages: { 

    test[]: "You must check at least 1 box"
  }
 });

推荐答案

您的代码有几个问题.

1).您的rules中缺少右括号}.

1) Missing a closing brace, }, within your rules.

2)在这种情况下,没有理由为required规则使用函数.默认情况下,该插件可以很好地处理checkboxradio输入,因此使用true就足够了.但是,这只会执行与原始功能相同的逻辑,并验证是否选中了至少一个.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3)如果您还只希望最多检查两个,则需要应用maxlength规则.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) messages选项缺少规则规范.它将起作用,但是一条自定义消息将应用于同一字段上的所有规则.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5)如果name属性包含方括号,则您必须将其用引号引起来.

5) If a name attribute contains brackets, you must enclose it within quotes.

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

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

这篇关于jQuery验证插件:“验证"复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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