jQuery Validation Plugin: Validating Checkboxes with Different Names

前端 未结 3 1828
鱼传尺愫
鱼传尺愫 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 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).

提交回复
热议问题