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

时间:2016-04-03 17:58:57

标签: javascript jquery jquery-validate

亲爱的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](&#34; 1&#34;指填写表格的第一人)。

现在这完美无缺:

    $.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 个答案:

答案 0 :(得分:0)

1)你缺少&#34;规则&#34;选项,

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/