My question is very similar to jQuery Validation using the class instead of the name value1. I want to validate a checkbox group, such that at least one needs to be checked. By default, both checkboxes are checked, but I want to ensure the user doesn’t uncheck both. The checkboxes are
<div>
<input type="checkbox" class="channel" name="web" checked />
<label for="web" class="check">Web</label>
<input type="checkbox" class="channel" name="mobile" checked />
<label for="mobile" class="check">Mobile</label>
</div>
The jquery I have is:
$("#searchForm").validate({
rules:{
...
...
...
}
});
$(".channel").rules("add", {
required: true,
minlength: 1
});
However, this doesn’t work quite as expected. If I check neither of the boxes or only the second one (mobile), the form won’t submit and I get an error message on the first one. What am I doing wrong?
I’m not sure if I’d use jQuery Validation for something like this, but if you just want to make sure that there is at least one checked checkbox in any group (whether that be class, or any other attribute), you can just check the length of any proper selector.
EDIT
Without using Validation, you can stop the submit by doing something like: