验证至少一个复选框(多组复选框) [英] validation at least one checkbox (multiple group of checkboxes)

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

问题描述

我知道已经在此处回答了
但是我的html如下所示:

I know this've been answered in here
But my html looks like below :

<div >
    <label> <input type="checkbox" name="service_area[]" value="colorado">colorado</label>
    <label> <input type="checkbox" name="service_area[]" value="michigan">michigan</label>
</div>

<div >
    <label> <input type="checkbox" name="fav[]" value="skiing">skiing</label>
    <label> <input type="checkbox" name="fav[]" value="volley">volley</label>
</div>

目标:

  • 名称必须具有数组,在这里:service_area []
  • 必须仅显示一条错误消息

如何实现?
每次我使用带有[[]]名称的jvalidate时,似乎它只反映到第一个元素,而不是所有元素.

How to achieve this ?
Each time I use jvalidate with '[]' name, it seems that it only reflects to the first element, not all elements.

我忘了提到我有多个复选框需要检查.
在html上方更新.
因此,rynhe的回答启发了我一点:

I forget to mention that I have more than one group of checkboxes that needed to be checked.
Updated above html.
So, rynhe answer inspired me a bit :

$.validator.addMethod(
  "atleastone",
  function(value, element, params) {
    return $('[name="' + element.name +'"]:checked').size() > 0;
  },
  'at least one');

  rules: {
    'service_area[]': {
      atleastone : true,
    },
    'fav[]': {
      atleastone : true,
    },        

最重要的部分是'service_area[]'. 上面的代码有效对我来说很好. 谢谢〜

The most important part is 'service_area[]'. Above code works fine for me. Thx ~

推荐答案

在这种情况下,您无需添加任何特殊方法.当一个组中的每个复选框共享相同的name时,只需使用required规则.由于名称包含方括号[],因此请用引号引起来.

You do not need to add any special methods in this case. When every checkbox in one group shares the same name, simply use the required rule. Since the names contain brackets, [], enclose it with quotes.

$(document).ready(function () {

    $('#myform').validate({
        rules: {
            'service_area[]': {
                required: true
            },
            'fav[]': {
                required: true
            }
        }
    });

});

  • service_area[]组中至少需要一个复选框.

    • At least one checkbox from service_area[] group is required.

      fav[]组中至少需要一个复选框.

      At least one checkbox from fav[] group is required.

      我使用errorPlacement选项将错误消息移到每个分组之前,但是您可以根据需要进行调整. 查看所有插件选项.

      I used the errorPlacement option to move the error message before each grouping but you can adjust as needed. See all plugin options.

      正在运行的演示: http://jsfiddle.net/AsuyC/

      Working DEMO: http://jsfiddle.net/AsuyC/

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

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