jQuery验证检查至少一个复选框 [英] jquery validate check at least one checkbox

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

问题描述

我有这样的东西:

<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吗?

I would like to validate that at least one checkbox (roles) should be checked, is it possible with jquery.validate ?

推荐答案

validate插件仅会验证当前/重点关注的元素.因此,您需要向验证器添加自定义规则,以验证所有复选框.类似于上面的答案.

The validate plugin will only validate the current/focused element.Therefore you will need to add a custom rule to the validator to validate all the checkboxes. Similar to the answer above.

$.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条消息.如果您单击另一个单独的复选框,然后为第二个复选框返回一个有效复选框,则尽管该表格是有效的,但原始复选框仍被标记为无效复选框,并且仍会显示错误消息. 在这种情况下,我一直只求自己显示和隐藏错误,然后验证器只负责不提交表单.

In addition, you will likely find the error message display, not quite sufficient. Only 1 checkbox is highlighted and only 1 message displayed. If you click another separate checkbox, which then returns a valid for the second checkbox, the original one is still marked as invalid, and the error message is still displayed, despite the form being valid. I have always resorted to just displaying and hiding the errors myself in this case.The validator then only takes care of not submitting the form.

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

The other option you have is to write a function that will change the value of a hidden input to be "valid" on the click of a checkbox and then attach the validation rule to the hidden element. This will only validate in the onSubmit event though, but will display and hide messages at the appropriate times. Those are about the only options that you can use with the validate plugin.

希望有帮助!

这篇关于jQuery验证检查至少一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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