jquery验证至少检查一个复选框

问题描述 投票:53回答:8

我有这样的事情:

<form>
<input name='roles' type='checkbox' value='1' />
<input name='roles' type='checkbox' value='2' />
<input name='roles' type='checkbox' value='3' />
<input name='roles' type='checkbox' value='4' />
<input name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
<form>

我想验证是否应该检查至少一个复选框(角色),是否可以使用jquery.validate?

javascript jquery jquery-validate
8个回答
37
投票

validate插件仅验证当前/焦点元素。因此,您需要向验证程序添加自定义规则以验证所有复选框。与上面的答案类似。

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

在元素上:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

此外,您可能会发现错误消息显示,还不够。仅突出显示1个复选框,仅显示1条消息。如果单击另一个单独的复选框,然后返回第二个复选框的有效复选框,则原始复选框仍标记为无效,并且尽管表单有效,仍会显示错误消息。在这种情况下,我总是使用显示和隐藏错误。验证器然后只负责不提交表单。

另一个选项是编写一个函数,在单击复选框时将隐藏输入的值更改为“有效”,然后将验证规则附加到隐藏元素。这只会在onSubmit事件中验证,但会在适当的时间显示和隐藏消息。这些是您可以使用validate插件的唯一选项。

希望有所帮助!


101
投票

来自https://github.com/ffmike/jquery-validate的例子

 <label for="spam_email">
     <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" validate="required:true, minlength:2" /> Spam via E-Mail </label>
 <label for="spam_phone">
     <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /> Spam via Phone </label>
 <label for="spam_mail">
     <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" /> Spam via Mail </label>
 <label for="spam[]" class="error">Please select at least two types of spam.</label>

只使用javascript在标签中没有字段“验证”:

$("#testform").validate({ 
    rules: { 
            "spam[]": { 
                    required: true, 
                    minlength: 1 
            } 
    }, 
    messages: { 
            "spam[]": "Please select at least two types of spam."
    } 
}); 

如果输入需要不同的名称,可以使用以下内容:

<input type="hidden" name="spam" id="spam"/>
<label for="spam_phone">
    <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam_phone" /> Spam via Phone</label>
<label for="spam_mail">
    <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam_mail" /> Spam via Mail </label>

使用Javascript:

 $("#testform").validate({ 
    rules: { 
        spam: { 
            required: function (element) {
                var boxes = $('.checkbox');
                if (boxes.filter(':checked').length == 0) {
                    return true;
                }
                return false;
            },
            minlength: 1 
        } 
    }, 
    messages: { 
            spam: "Please select at least two types of spam."
    } 
}); 

我在输入之前添加了隐藏输入,如果没有选中的复选框,则将其设置为“required”


11
投票

嗯,首先你的id属性必须是唯一的,你的代码很可能是

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

对于你的问题:

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

但请记住,JavaScript表单验证只是指示性的,所有验证必须在服务器端完成。


6
投票
$("#idform").validate({
    rules: {            
        'roles': {
            required: true,
        },
    },
    messages: {            
        'roles': {
            required: "One Option please",
        },
    }
});

4
投票

这就是我过去处理它的方式:

$().ready(function() {                                                      
    $("#contact").validate({
        submitHandler: function(form) {
            // see if selectone is even being used
            var boxes = $('.selectone:checkbox');
            if(boxes.length > 0) {
                if( $('.selectone:checkbox:checked').length < 1) {
                    alert('Please select at least one checkbox');
                    boxes[0].focus();
                    return false;
                }
            }
            form.submit();
        }
    }); 

});

2
投票

您很可能希望在复选框旁边有一个文本。在这种情况下,您可以将复选框放在标签内,如下所示:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

问题是,当显示错误消息时,它将在复选框之后但在文本之前插入,使其无法读取。为了解决这个问题,我更改了错误放置功能:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

这取决于你的布局,但我做的是为复选框控件设置一个特殊的错误位置。我得到复选框的父级,这是一个标签,然后我得到它的父级,在我的情况下这是一个div。这样,错误就位于复选框控件列表下方。


2
投票

sir_neanderthal已经发布了一个很好的答案。

我只想指出,如果您想为输入使用不同的名称,您还可以使用(或只是复制方法)require_from_group method来自官方jQuery验证additional-methods.js(link to CDN for version 1.13.1)。


0
投票

确保input-name[]在规则集中的引号中。花了我几个小时才弄明白这一部分。

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

在这里阅读更多... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

© www.soinside.com 2019 - 2024. All rights reserved.