jQuery Validation plugin: checkbox groups and error message issues
Posted
by boomturn
on Stack Overflow
See other posts from Stack Overflow
or by boomturn
Published on 2010-02-24T16:14:19Z
Indexed on
2010/06/17
18:03 UTC
Read the original article
Hit count: 357
I've put together a form using the jQuery Validation plugin, and all inputs are fine with working validation and error messages – except for checkboxes. I have two checkbox problems.
The first is that the Validation plugin API doesn't seem to handle checkboxes in grouped contexts (I'm using fieldsets for grouping). Found several approaches to the issue here, including reference to a post by Rebecca Murphey for a more general case using a custom method and class. Adapting that to this situation:
jQuery.validator.addMethod('required_group', function(val, el) {
var fieldParent = $(el).closest('fieldset');
return fieldParent.find('.required_group:checked').length;
});
jQuery.validator.addClassRules('required_group', {
'required_group': true
});
jQuery.validator.messages.required_group = 'Please check at least one box.';
This sort of works, but produces error messages on every checkbox, and only removes them as each box is clicked. This is not an acceptable situation for the user, who can only get rid of them by clicking false positives. Ideally, I guess what's needed is something to prevent or eliminate extra messages before they are displayed and use errorPlacement to display a single error message in the parent fieldset, that would then be removed with a click on any checkbox. Less ideally, maybe they would all display but an event handler could turn off the full set of redundant messages with a click, which is what this approach offered by tvanfosson appears to do. (Another customized approach here, but I couldn't get it to work.) I guess I should also note this form requires the checkboxes to have different names.
My second problem is that one of the fieldsets with checkboxes in the form also contains a nested fieldset of checkboxes under one of the outer checkboxes. So in addition to the first-level one-box-checked requirement, if the particular checkbox containing the second-level checkboxes is checked, then at least one of the second-level boxes must be checked. Not sure about the right approach; I'm guessing what needs to happen (following the above scheme) is that the trigger checkbox would use toggleClass to add/remove 'required_group' class to all the checkboxes in the subfield, which would then (hopefully) behave the same as the parent field:
$("#triggerCheckbox").click(function () {
$(this).find(":checkbox").toggleClass("required_group");
});
Any suggestions or ideas welcome. I'm well beyond my limited jQuery skills on this one and would be happy to hear that I missed simple, elegant and/or obvious ways to do this!
© Stack Overflow or respective owner