jQuery Validation Plugin: Validating Checkboxes with Different Names

前端 未结 3 1822
鱼传尺愫
鱼传尺愫 2021-02-03 16:38

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\'.



        
相关标签:
3条回答
  • 2021-02-03 16:53

    I think @Anurag was on the right path. Check out this working version...

    http://jsfiddle.net/Y23ec/

    Same idea just a different way of doing it.

    <form name="itemForm" id="itemForm" method="post">
    <input type="checkbox" name="check1" id="check1" class="require-one validate-checkbox-oneormore" value="1" />
    <input type="checkbox" name="check2" id="check2" class="require-one validate-checkbox-oneormore" value="2" />
    <input type="text" class="required" />
    <input type="submit" />
    </form>
    
    jQuery(document).ready(function () {
        $.validator.addMethod('validate-checkbox-oneormore', function (value) {
            return $('.require-one:checked').size() != 0; }, 'need a value');
    
        jQuery('#itemForm').validate({});
    });
    
    0 讨论(0)
  • 2021-02-03 16:54

    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/

    0 讨论(0)
  • 2021-02-03 17:05

    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).

    0 讨论(0)
提交回复
热议问题