views:

765

answers:

3

Hello all, this is my first post here on stackoverflow and am very impressed by the site!

My question is about the jQuery Validation plugin...specifically about the minLength method. I have a group of checkboxes and i want to know if at least 2 boxes were checked.

http://docs.jquery.com/Plugins/Validation/Methods/minlength#length

at this link there is documentation about the minLength method being used with a regular input box, but not a checkbox. Can anyone help me on how to use if for checkboxes?

Thanks in advance,
Ian McCullough

A: 

It isn't usable for checkboxes. The concept of 'length' it refers to is string length. You would need to make a custom validation method to get the behavior you want, or possibly do something fancy with dependency expressions in required.

karim79's answer is a start on what you'd need to put in a custom validation method. (The condition, not the alert.)

chaos
@ the link i posted in my post it states..."Works with text inputs, selects and checkboxes."
Ian McCullough
+1  A: 

I don't know about the jQuery validation plugin, but I imagine you could do something like:

if($('.myCheckBoxes :checked').length > 2) {
   alert('at least two have been checked');
}

assuming your checkboxes have a class of myCheckBoxes

or something like:

if($("input[type='checkbox'] :checked").length > 2) {
   alert('at least two have been checked');
}
karim79
+1  A: 

There isn't a default method. Fortunately you can add it.

jQuery.validator.addMethod('has2selected',function(value, element) {
return $(element).filter(':checked').length >= 2;
}, 'the error message');

EDIT: I read again the documentation and the minlength should work (if wasn't the case the above code can make the job). You didn't post the code so I'm not sure if this is causing the error, but in your post is minLength it has to be minlength.

Daniel Moura