Using the jQuery Validation Plugin to choose atleast one CheckBox before submitting the Form

Let us see how to use the jQuery Validation Plugin to choose atleast one checkbox before submitting the form

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<
head>
<
style type="text/css">
label.error {
float: none; color: red;
padding-left: .3em; vertical-align: top;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>

<
script type="text/javascript">
$.validator.addMethod('onecheck', function(value, ele) {
return $("input:checked").length >= 1;
}, 'Please Select Atleast One CheckBox')

$(document).ready(function() {
$("#form1").validate({
rules: {
bev: {
onecheck: true
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
}
});
});
</script>
<
title></title>
</
head>
<
body>
<
form id="form1">
<
div id="chkboxes">
<
input type="checkbox" name="bev" value="cream" />With cream<br />
<
input type="checkbox" name="bev" value="sugar" />With sugar<br />
<
input type="checkbox" name="bev" value="sugar" />With sugar<br />
</
div>
<
div id="err"></div>
<
input id="btnSubmit" type="submit" value="submit" />
</
form>
</
body>
</
html>

When the user tries to submit the form without selecting a checkbox, the validation fires and the following error message gets displayed

Select atlease one checkbox

The error disappears when a checkbox is selected and the user can now submit the form






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

Did u know how to make this work with multiple select? like:

bev[ ]

?

alexkwatson said...

Yes, you just put 'bev[]' (single quotes included) instead of bev in the validate function.