jQuery 不同名称的复选框组的验证方法
jQuery validation method for group of check boxes with different names
我有一组复选框,由于与另一个平台的集成,它们必须有单独的名称,尽管它们都是相关的。
<div class="form-group col-xs-6 checkbox-group">
<label class="block input-group" for="Field5">Type of Insurance<span class="required-mark">*</span></label>
<span><input type="checkbox" name="Field5" class="validate checkbox-group" value="Auto" >Auto</span>
<span><input type="checkbox" name="Field6" class="validate checkbox-group" value="Home" >Home</span>
<span><input type="checkbox" name="Field7" class="validate checkbox-group" value="Auto & Home" >Home</span>
<span><input type="checkbox" name="Field8" class="validate checkbox-group" value="Renters">Condo, Co-op,Renters</span>
</div>
通常,您可以使用 Field[] 并在 jQuery 验证规则内对其进行验证,并将其设置为必需。我无法将每个字段都设置为必填,因为只有一个复选框必须被选中,但它们也都可以被选中。
这让我相信我需要一个自定义方法。
jQuery.validator.addMethod("checkone", function(){
if( $(".checkbox-group").is(":checked") ){
return true;
}
return false;
}, "Please check at least of one");
我似乎想不通的是如何让屏幕上只显示一条错误消息。验证有效,但在选中 none 个复选框时会输出四个单独的错误。
规则添加到每个复选框
$(this).rules('add', { checkone: true }
);
What I can't seem to figure out is how to make just one error message appear on screen. The validation works but outputs four separate errors when none of the checkboxes are checked.
您可以在 .validate()
中使用 the groups
option 将所有错误消息合并为一个。
$('#yourForm').validate({
groups: {
anyName: "Field5 Field6 Field7 Field8"
},
// other options, etc.
});
然后您可以在 errorPlacement
中使用条件函数将其放置在布局中的任何位置。
我有一组复选框,由于与另一个平台的集成,它们必须有单独的名称,尽管它们都是相关的。
<div class="form-group col-xs-6 checkbox-group">
<label class="block input-group" for="Field5">Type of Insurance<span class="required-mark">*</span></label>
<span><input type="checkbox" name="Field5" class="validate checkbox-group" value="Auto" >Auto</span>
<span><input type="checkbox" name="Field6" class="validate checkbox-group" value="Home" >Home</span>
<span><input type="checkbox" name="Field7" class="validate checkbox-group" value="Auto & Home" >Home</span>
<span><input type="checkbox" name="Field8" class="validate checkbox-group" value="Renters">Condo, Co-op,Renters</span>
</div>
通常,您可以使用 Field[] 并在 jQuery 验证规则内对其进行验证,并将其设置为必需。我无法将每个字段都设置为必填,因为只有一个复选框必须被选中,但它们也都可以被选中。
这让我相信我需要一个自定义方法。
jQuery.validator.addMethod("checkone", function(){
if( $(".checkbox-group").is(":checked") ){
return true;
}
return false;
}, "Please check at least of one");
我似乎想不通的是如何让屏幕上只显示一条错误消息。验证有效,但在选中 none 个复选框时会输出四个单独的错误。
规则添加到每个复选框
$(this).rules('add', { checkone: true }
);
What I can't seem to figure out is how to make just one error message appear on screen. The validation works but outputs four separate errors when none of the checkboxes are checked.
您可以在 .validate()
中使用 the groups
option 将所有错误消息合并为一个。
$('#yourForm').validate({
groups: {
anyName: "Field5 Field6 Field7 Field8"
},
// other options, etc.
});
然后您可以在 errorPlacement
中使用条件函数将其放置在布局中的任何位置。