jQuery Validation Plugin: Validating Checkboxes with Different Names

19,700

Solution 1

Justin has the correct answer. Here is an extension that consolidates the error reporting for all the check boxes into a single message:

http://jsfiddle.net/twd8j0tu/

$.validator.addMethod('require-one', function (value) {
              return $('.require-one:checked').size() > 0; }, 'Please check at least one box.');

var checkboxes = $('.require-one');
var checkbox_names = $.map(checkboxes, function(e,i) { return $(e).attr("name")}).join(" ");

$("#itemForm").validate({
    groups: { checks: checkbox_names },
    errorPlacement: function(error, element) {
             if (element.attr("type") == "checkbox")
               error.insertAfter(checkboxes.last());
             else
               error.insertAfter(element);
    }         
});

(Please note that this code doesn't seem to work after jquery.validate.js version 1.10.0. You will have to modify it for later versions).

Solution 2

Swatting a fly with a rocket launcher?

$('.require-one:checked').size() == 0;

Apply the rule on any one of the checkboxes using it's name. For the form to be valid, this checkbox must pass validations. For this checkbox to be valid, at least one of the 4 checkboxes must be checked.

$("#itemForm").validate({
rules: { 
    'check1': {  
        required: {
            depends: function(element) {
                return $('.require-one:checked').size() == 0;
            }
        } 
    } 
}
});

Updated 2:

http://jsfiddle.net/MkPtP/1/

Share:
19,700
Michael
Author by

Michael

Updated on June 05, 2022

Comments

  • Michael
    Michael almost 2 years

    I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked.

    I have set the class on all of them to 'require-one'.

    <html>
    <head>
    <script src="scripts/lib/jquery.js" type="text/javascript"></script>
    <script src="scripts/jquery.validate.js" type="text/javascript"></script>
    
    <script language="JavaScript" type="text/javascript">
     $(document).ready(function(){
        $("#itemForm").validate({
    
    rules: { 
        check1: {  
            required : {  
                depends: function(element) {  
                    $('.require-one:checked').size() == 0; 
                }  
            } 
        } 
    }
        });
      });
    </script>
    
    </head>
    <body>
    <form name="itemForm" id="itemForm" method="post">
    <input type="checkbox" name="check1" id="check1" class="require-one" value="1" />
    <input type="checkbox" name="check2" id="check2" class="require-one" value="2" />
    <input type="text" class="required" />
    <input type="submit" />
    </form>
    </body>
    </html>
    

    If you put in 'return' before the $('.require-one:checked').size() == 0; However, now my problem is the error message will only disappear if Checkbox #1 is selected. If Checkbox #2 is selected it will not disappear, but will submit. How do I remove the error if any of the checkboxes are checked?

    rules: { 
        'nameOfAnyCheckbox': {  
            required : {  
                depends: function(element) {  
                  return $('.require-one:checked').size() == 0; 
                }  
            } 
        }
    
  • Michael
    Michael about 14 years
    That looks amazing! I am new to jQuery though. How would I put that into the jQuery code instead of an onClick event?
  • Chance
    Chance about 14 years
    check the jsfiddle link - jsfiddle.net/zQg8m. do you have to integrate this with the validation plugin?
  • Michael
    Michael about 14 years
    Yes, that's what I meant, sorry! With the validation plugin. Do I put it under a Rules heading?
  • Michael
    Michael about 14 years
    The code makes sense, but is not working (see my edit above). It will validate the text box, but not the checkboxes.
  • Chance
    Chance about 14 years
    I haven't used jquery validation before, but it has something to do with the use of depends. I've removed that and just used a callback function on required. Check updated code. link on jsfiddle is updated too.
  • Chance
    Chance about 14 years
    btw, the above code looks correct.. pasted the same thing on jsfiddle.net/MkPtP/1 and it works.. i was wrong about not using depends
  • Michael
    Michael about 14 years
    Yes, it for sure works (but jsfiddle should be '==' not '>'). However, now the error message will only disappear if Checkbox #1 is selected. If Checkbox #2 is selected it will not disappear, but will submit. How do we remove the error class when any of the checkboxes are selected?
  • devth
    devth about 14 years
    Yeah, doesn't look like a valid solution. I'm trying to figure out the same thing...
  • crenshaw-dev
    crenshaw-dev over 6 years
    Karen, I'm having trouble with this solution, and the JSFiddle seems broken. Submitting the form returns {"error": "Shell form does not validate.... That seems to be JSFiddle-generated rather than jQuery-generated.
  • Karen Zilles
    Karen Zilles over 6 years
    @mac9416 The link to the validate.js library was broken in the fiddle, but in the process of fixing it I found out that the code doesn't run as is in validate versions after 1.10.0. I suspect that the changes required would be minor.
  • Radmation
    Radmation over 5 years
    I have to use length otherwise I get this error: Uncaught TypeError: $(...).size is not a function. So it looks like this: $('.require-one:checked').length == 0;