views:

635

answers:

1

I need to validate that atleast one check box is selected from a list of checkboxes using jQuery Validation Plugin. Since the checkboxes are part of a ASP.NET GridView Control, the names of these checkboxes will be different, which makes setting up the rules for the validation plugin complex since it expects the name for the rule. I have searched around and found the below questions

I think the first question is a much better solution, but i still feel that it is not the right way to do. does anybody else have any more options for this problem.

+1  A: 

How about a complex rule that only makes the item required if no other checkboxes have been checked.

rules: {
   'require-one': {
       required : {
           depends: function(element) {
                       var allBoxes = $('.require-one');
                       if (allBoxes.filter(':checked').length == 0) {
                          if (allBoxes.eq(element).length != 0) {
                              return true;
                          }
                       }
                       return false;
                    }
       }
    }
}

Then you'd apply the require-one class to each checkbox in the set. The first one would be required if none of the boxes where checked.

tvanfosson
@tvanfosson, my scenario is to validate atleast one checkbox is selected, not that only one checkbox is selected (i am not using it as a Radio button Group) Your rule seems to indicate that only one should be selectedi did go the class approach way, the disadvantage seemed to be that the validation will be called for each checkbox, and so will the message, even though i use a container for showing an error message.
Dinesh Manne
No. If at least one checkbox is checked, then none are required. If none are checked, then all are required -- and since they are not checked it will result in a validation error for each. It does have the disadvantage of having a message for each.
tvanfosson
You could adjust this to also return true for the first element, if none are checked. I'll adjust.
tvanfosson