使用jQuery验证插件验证一组复选框

Validating a Group of Checkboxes using the jQuery validation plugin

本文关键字:验证 一组 复选框 jQuery 插件 使用      更新时间:2023-09-26

如何在使用jquery验证插件时验证一组复选框?

我为text使用的代码如下,但是如何为一组复选框完成?

<form id="newItem" action="formProcess.php" method="post">
    <input type="text" class="itemTitle" name="itemTitle" value="" autocomplete="off"><br>
    <label for="itemTitle" generated="true" class="error itemTitle" style=""></label><br>
    <input type="checkbox" name="country[]" value="US" class="destinations"><br>
    <input type="checkbox" name="country[]" value="GB" class="destinations"><br>
    <input type="checkbox" name="country[]" value="CA" class="destinations"><br>
    <input type="checkbox" name="country[]" value="SE" class="destinations"><br>
    <label for="destinations" generated="true" class="error destinations" style=""></label><br>
<input type="submit" name="Submit" value="Submit">
</form>;
$("#newItem").validate({
    rules: {
        itemTitle: {
            required: true,
            minlength: 3,
            maxlength: 60
        },
    // How is it done for a group of check boxes?
    // I'd like at least 1 destination to be selected, and a maximum of 3. This cannot be left blank.

    messages: {
        itemTitle: {
            required: "Please enter a valid name",
            minlength: "Minimum length required is 3 characters",
            maxlength: "Maximum length allowed 51 characters"
        },
    },
submitHandler: function() {
// Other code follows

试试这个

    $("#newItem").validate({
    rules: {
        "country[]": {
            required: true,
            minlength: 1,
            maxlength: 3
        }
    },
    messages: {
        "country[]": {
            required: "Check atleast 1",
            minlength: "Min 1",
            maxlength: "Max only 3"
        }
    }
});
演示