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

时间:2014-03-28 11:14:22

标签: javascript jquery jquery-validate

如何在使用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

1 个答案:

答案 0 :(得分:1)

试试这个

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

});

DEMO