How to validate a form with multiple checkboxes to have atleast one checked

jalperin picture jalperin · Oct 8, 2009 · Viewed 136.7k times · Source

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?

Answer

Vincent P picture Vincent P · Nov 18, 2009
  $('#subscribeForm').validate( {
      rules: {
          list: {
              required: true,
              minlength: 1
          }
       }
   });

I think this will make sure at least one is checked.