jquery validate check at least one checkbox

Example from https://github.com/ffmike/jquery-validate

 <label for="spam_email">
     <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" validate="required:true, minlength:2" /> Spam via E-Mail </label>
 <label for="spam_phone">
     <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /> Spam via Phone </label>
 <label for="spam_mail">
     <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" /> Spam via Mail </label>
 <label for="spam[]" class="error">Please select at least two types of spam.</label>

The same without field “validate” in tags only using javascript:

$("#testform").validate({ 
    rules: { 
            "spam[]": { 
                    required: true, 
                    minlength: 1 
            } 
    }, 
    messages: { 
            "spam[]": "Please select at least two types of spam."
    } 
}); 

And if you need different names for inputs, you can use somethig like this:

<input type="hidden" name="spam" id="spam"/>
<label for="spam_phone">
    <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam_phone" /> Spam via Phone</label>
<label for="spam_mail">
    <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam_mail" /> Spam via Mail </label>

Javascript:

 $("#testform").validate({ 
    rules: { 
        spam: { 
            required: function (element) {
                var boxes = $('.checkbox');
                if (boxes.filter(':checked').length == 0) {
                    return true;
                }
                return false;
            },
            minlength: 1 
        } 
    }, 
    messages: { 
            spam: "Please select at least two types of spam."
    } 
}); 

I have added hidden input before inputs and setting it to “required” if there is no selected checkboxes

Leave a Comment