验证至少一个复选框

时间:2012-07-16 20:58:14

标签: jquery asp.net-mvc-3 jquery-validate

我看过其他一些帖子有同样的问题,但无法让解决方案适合我,所以我发布了自己的问题。

让我先说一下我是JQuery和MVC的新手。我有3个复选框,我需要确保至少检查其中一个。我有一些使用Jquery自定义验证的工作。但它在验证摘要中显示3条消息。我希望它只显示一条消息,如果可能,则不在验证摘要中。我怎么能做到这一点?

html代码

<label for="river1">river1</label>
<input checked="checked" class="checkbox" data-val="true" data-val-required="The     river1 field is required." id="river1" name="river1" type="checkbox" value="true" />
<input name="river1" type="hidden" value="false" /><br />

<label for="river2">river2</label>
<input checked="checked" class="checkbox" data-val="true" data-val-required="The river2 field is required." id="river2" name="river2" type="checkbox" value="true" />
<input name="river2" type="hidden" value="false" /><br />

<label for="river3">river3</label>
<input checked="checked" class="checkbox" data-val="true" data-val-required="The river3 field is required." id="river3" name="river3" type="checkbox" value="true" />
<input name="river3" type="hidden" value="false" /><br />

JQuery的

$.validator.addMethod("checkbox", function (value, element) {
  return $('.checkbox:checked').length > 0;
  }, 'At least one river must be selected.');

1 个答案:

答案 0 :(得分:14)

工作演示 http://jsfiddle.net/RGUTv/

已更新 - 2015年1月12日=&gt; http://jsfiddle.net/r24kcvz6/ CDN已被http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js - 您可以通过取消所有复选框并点击submit按钮来复制行为。

<强>码

$.validator.addMethod('require-one', function(value) {
    return $('.require-one:checked').size() > 0;
}, 'Please check at least one box.');

var checkboxes = $('.require-one');
var checkbox_names = $.map(checkboxes, function(e, i) {
    return $(e).attr("name")
}).join(" ");

$("#itemForm").validate({
    groups: {
        checks: checkbox_names
    },
    errorPlacement: function(error, element) {
        if (element.attr("type") == "checkbox") error.insertAfter(checkboxes.last());
        else error.insertAfter(element);
    }
});

<强> HTML

<form name="itemForm" id="itemForm" method="post">

<label for="river1">river1</label>
<input checked="checked" data-val="true" data-val-required="The     river1 field is required." id="river1" name="river1" type="checkbox" value="true" class="require-one" />
<input name="river1" type="hidden" value="false" /><br />

<label for="river2">river2</label>
<input checked="checked" data-val="true" data-val-required="The river2 field is required." id="river2" name="river2" type="checkbox" value="true" class="require-one" />
<input name="river2" type="hidden" value="false" /><br />

<label for="river3">river3</label>
<input checked="checked" data-val="true" data-val-required="The river3 field is required." id="river3" name="river3" type="checkbox" value="true" class="require-one" />
<input name="river3" type="hidden" value="false" /><br />

<input type="submit" />
</form>

图片如果您取消勾选验证将触发

enter image description here