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 submitted. Here's my jquery code:
$().ready(function() {
$("#subscribeForm").validate({
rules: { list: {required: "#list0:checked"} },
messages: { list: "Please select at least one newsletter"}
});
});
and here's the html form:
<form action="" method="GET" id="subscribeForm">
<fieldset id="cbgroup">
<div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div>
<div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div>
<div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div>
</fieldset>
<input name="submit" type="submit" value="submit">
The problem is that the form submits even if nothing is checked. How can I resolve this?
This question is related to
javascript
html
checkbox
jquery-validate
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.
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) {_x000D_
var $parent = $(element).closest('.checkbox_wrapper');_x000D_
if($parent.find('.checkbox_item').is(':checked')) return true;_x000D_
return false;_x000D_
}, 'Please at least select one');
_x000D_
<div class="checkbox_wrapper">_x000D_
<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>_x000D_
<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>_x000D_
</div>
_x000D_
Good example without custom validate methods, but with metadata plugin and some extra html.
$('#subscribeForm').validate( {
rules: {
list: {
required: true,
minlength: 1
}
}
});
I think this will make sure at least one is checked.
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();
});
I had a slighlty different scenario. My checkboxes were created in dynamic and they were not of same group. But atleast any one of them had to be checked. My approach (never say this is perfect), I created a genric validator for all of them:
jQuery.validator.addMethod("validatorName", function(value, element) {
if (($('input:checkbox[name=chkBox1]:checked').val() == "Val1") ||
($('input:checkbox[name=chkBox2]:checked').val() == "Val2") ||
($('input:checkbox[name=chkBox3]:checked').val() == "Val3"))
{
return true;
}
else
{
return false;
}
}, "Please Select any one value");
Now I had to associate each of the chkbox to this one single validator.
Again I had to trigger the validation when any of the checkboxes were clicked triggering the validator.
$('#piRequest input:checkbox[name=chkBox1]').click(function(e){
$("#myform").valid();
});
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
}
});
});
The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:
$.validator.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 at least one option');
I had to do the same thing and this is what I wrote.I made it more flexible in my case as I had multiple group of check boxes to check.
// param: reqNum number of checkboxes to select
$.fn.checkboxValidate = function(reqNum){
var fields = this.serializeArray();
return (fields.length < reqNum) ? 'invalid' : 'valid';
}
then you can pass this function to check multiple group of checkboxes with multiple rules.
// helper function to create error
function err(msg){
alert("Please select a " + msg + " preference.");
}
$('#reg').submit(function(e){
//needs at lease 2 checkboxes to be selected
if($("input.region, input.music").checkboxValidate(2) == 'invalid'){
err("Region and Music");
}
});
if (
document.forms["form"]["mon"].checked==false &&
document.forms["form"]["tues"].checked==false &&
document.forms["form"]["wed"].checked==false &&
document.forms["form"]["thrs"].checked==false &&
document.forms["form"]["fri"].checked==false
) {
alert("Select at least One Day into Five Days");
return false;
}
Source: Stackoverflow.com