I\'m trying to validate a form using the validate plugin for jquery. I want to require that the user check at least one checkbox in a group in order for the form to be sub
Here is the a quick solution for multiple checkbox validation using jquery validation plugin:
jQuery.validator.addMethod('atLeastOneChecked', function(value, element) {
return ($('.cbgroup input:checked').length > 0);
});
$('#subscribeForm').validate({
rules: {
list0: { atLeastOneChecked: true }
},
messages: {
list0: { 'Please check at least one option' }
}
});
$('.cbgroup input').click(function() {
$('#list0').valid();
});
$('#subscribeForm').validate( {
rules: {
list: {
required: true,
minlength: 1
}
}
});
I think this will make sure at least one is checked.
How about this:
$(document).ready(function() {
$('#subscribeForm').submit(function() {
var $fields = $(this).find('input[name="list"]:checked');
if (!$fields.length) {
alert('You must check at least one box!');
return false; // The form will *not* submit
}
});
});
I checked all answers and even in other similar questions, I tried to find optimal way with help of html class and custom rule.
my html structure for multiple checkboxes are like this
$.validator.addMethod('multicheckbox_rule', function (value, element) {
var $parent = $(element).closest('.checkbox_wrapper');
if($parent.find('.checkbox_item').is(':checked')) return true;
return false;
}, 'Please at least select one');
<div class="checkbox_wrapper">
<label for="checkbox-1"><input class="checkbox_item" id="checkbox-1" name="checkbox_item[1]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>
<label for="checkbox-2"><input class="checkbox_item" id="checkbox-2" name="checkbox_item[2]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>
</div>
How about this
$.validate.addMethod(cb_selectone,
function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
},
'Please select a least one')
Now you ca do
$.validate({rules:{checklist:"cb_selectone"}});
You can even go further a specify the minimum number to select with a third param in the callback function.I have not tested it yet so tell me if it works.