Question

How do I validate a group of check boxes when using the jquery validation plugin?

The code I use for text is below, but how is it done for a group of checkboxes?

<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
Was it helpful?

Solution

Try this

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

});

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top