views:

54

answers:

3

I have something like this:

<form>
<input id='roles' name='roles' type='checkbox' value='1' />
<input id='roles' name='roles' type='checkbox' value='2' />
<input id='roles' name='roles' type='checkbox' value='3' />
<input id='roles' name='roles' type='checkbox' value='4' />
<input id='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
<form>

I would like to validate that at least one checkbox (roles) should be checked, is it possible with jquery.validate ?

+1  A: 

Mmm first your id attributes must be unique, your code is likely to be

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

For your problem :

if($('.roles:checkbox:checked).length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.

Romain Deveaud
actually I don't care about the ids I need the same name for them so I would a get the result at the server side in this form "1,2,5", I'm using jquery.validate for client-side validation, and would like to make it validate my form in this scenario
Omu
+1  A: 

The validate plugin will only validate the current/focused element.Therefore you will need to add a custom rule to the validator to validate all the checkboxes. Similar to the answer above.

$.validator.addMethod("roles", function(value, elem, param) {
    if($(".roles:checkbox:checked").length > 0){
       return true;
   }else {
       return false;
   }
},"You must select at least one!");

And on the element:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

In addition, you will likely find the error message display, not quite sufficient. Only 1 checkbox is highlighted and only 1 message displayed. If you click another separate checkbox, which then returns a valid for the second checkbox, the original one is still marked as invalid, and the error message is still displayed, despite the form being valid. I have always resorted to just displaying and hiding the errors myself in this case.The validator then only takes care of not submitting the form.

The other option you have is to write a function that will change the value of a hidden input to be "valid" on the click of a checkbox and then attach the validation rule to the hidden element. This will only validate in the onSubmit event though, but will display and hide messages at the appropriate times. Those are about the only options that you can use with the validate plugin.

Hope that helps!

menzies