jQuery Validation: validate atleast one checkbox is selected from a list where names are different

流过昼夜 提交于 2020-01-04 07:44:56

问题


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

  • Question 1710486
  • Question 1136507

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:


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.



来源:https://stackoverflow.com/questions/1734840/jquery-validation-validate-atleast-one-checkbox-is-selected-from-a-list-where-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!