繁体   English   中英

jQuery验证其中字段名称包含方括号的组

[英]jQuery validate a group where field names contain brackets

亲爱的JavaScript专业人士,

我有一个HTML表单,其中包含两组复选框。 该组中的一个包含复选框,应选中其中一个以通过jQuery验证。 另一个组不是必须选择的。

First group (at least one checkbox should be selected):
<input type="checkbox" name="appSourceFirstoption[1]" value="Answer 1" id="appSourceFirstoption" />
<input type="checkbox" name="appSourceSecondoption[1]" value="Answer 2" id="appSourceSecondoption" />
<input type="checkbox" name="appSourceThirdoption[1]" value="Answer 3" id="appSourceThirdoption" />


Second group (these checkboxes are voluntary to select):
<input type="checkbox" name="appSourceVoluntaryFirst[1]" value="Answer 1" id="appSourceVoluntaryFirst" />
<input type="checkbox" name="appSourceVoluntarySecond[1]" value="Answer 2" id="appSourceVoluntarySecond" />
<input type="checkbox" name="appSourceVoluntaryThird[1]" value="Answer 3" id="appSourceVoluntaryThird" />

复选框的名称包含数组符号,例如checkboxName [1](“ 1”表示填写表格的第一个人)。

现在,这很完美:

    $.validator.addMethod('checkbox', function(value) {
     return $('input[type=checkbox]:checked').size() > 0;
    }, 'Please select at least one.');

但它适用于所有复选框(因此,即使从第二个自愿组中选择了一个复选框,也可以通过验证)。

如果我尝试对强制性复选框进行分组,则无法使用。 我认为这可能是由于它们的名称包含如上所述的[]。

    // adding the group 
    $.validator.addMethod("checkbox_1", function(value, element) {
    return $('.checkbox_1:checked').length > 0;
    }, 'Please select at least one.');


    $('#step').validate({

    // grouping the checkboxes together
    groups: {
    checkbox_1: "appSourceFirstoption[1] appSourceSecondoption[1] appSourceThirdoption[1]"
    },

    // applying the group rules to just one of the checkbox
    "appSourceFirstoption[1]" : { checkbox_1: true },
    }

你们对我如何解决这个问题有任何想法吗?

1)您缺少“规则”选项,

rules: {
        "appSourceFirstoption[1]": { checkbox_1: true }
       }

2)更改$('.checkbox_1:checked').length > 0;

$('input[type=checkbox]:checked').length > 0;

完整代码

$(document).ready(function () {


$('#step').validate({

    // grouping the checkboxes together
    groups: {
              checkbox_1: "appSourceFirstoption[1] appSourceSecondoption[1] appSourceThirdoption[1]"
            },

    // applying the group rules to just one of the checkbox
    rules: {
              "appSourceFirstoption[1]": { checkbox_1: true }
           }
});

$.validator.addMethod("checkbox_1", function (value, element) {
    return $('input[type=checkbox]:checked').length > 0;
}, 'Please select at least one.');


});

工作提琴。 -https://jsfiddle.net/8ukbf3wy/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM