jQuery Validation at least one checkbox is selected

后端 未结 5 1702
鱼传尺愫
鱼传尺愫 2021-01-15 02:05

I have the following piece of html code for form checkboxes

5条回答
  •  无人共我
    2021-01-15 02:50

    Quote OP:

    "I want to make sure that at least one of the check boxes is selected."

    If you want to use the jQuery Validate plugin, and all checkboxes have a different name, simply use the require_from_group method that's part of the additional-methods.js file.

    Since you already have a common class on these checkboxes called require-one, it's even easier.

    $('#form').validate({
        rules: {
            fieldname: {
                require_from_group: [1, '.require-one']
            },
            // declare same rule on all eight checkboxes
            ....
            ....
        }
    });
    

    However, rather than declare all eight of these within .validate(), you can use the .rules('add') method inside of a jQuery .each() to declare them all at once.

    $('.require-one').each(function () {
        $(this).rules('add', {
            require_from_group: [1, this],
            messages: {
                require_from_group: "please check one"
            }
        });
    });
    

    Then to combine all eight messages into one, use the groups option...

    $('#form').validate({
        groups: {  // combine these error messages into one
            checkboxes: 'allwines beer redwines cider whitewines spirits sparkling fortified'
        }
    });
    

    Working DEMO: http://jsfiddle.net/JVWu2/1/

    Placing your error message into the #error_msg3 error box is no different than placing any of your other jQuery Validate messages.

提交回复
热议问题