A common way to arrayify a group of checkboxes (or radio inputs) is to use name=*[].
Assign a rule to the "Notes8[]" prop selector and use minlength: 1 property:
jQuery(function($) { // DOM ready and $ alias in scope
$("#myForm").validate({
rules: {
"Notes8[]": {
required: true,
minlength: 1
}
},
messages: {
"Notes8[]": "Select at least one"
}
});
});
<form id="myForm">
<label>
<input class="mandatory Notes8_group" name="Notes8[]" type="checkbox" value="n8_1_yes"> Option 1
</label>
<label>
<input class="mandatory Notes8_group" name="Notes8[]" type="checkbox" value="n8_2_yes"> Option 2
</label>
<label>
<input class="mandatory Notes8_group" name="Notes8[]" type="checkbox" value="n8_3_yes"> Option 3
</label>
<button type="submit">SEND</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
Kudos to: https://stackoverflow.com/a/4120320/383904
Custom validator for multiple checkboxes
If you want to build your custom validator this should give you a go:
jQuery(function($) { // DOM ready and $ alias in scope
function validateMultiple (selector, n, isExactlyN) {
const totChecked = $(selector).filter(':checked').length;
return !(isExactlyN ? totChecked == n : totChecked >= n);
}
$('#myForm').on('submit', function(ev) {
if (validateMultiple('.Notes8_group', 1)) {
ev.preventDefault();
alert("Select at least one"); // Your custom error here
}
});
});
<form id="myForm">
<label>
<input class="mandatory Notes8_group" name="Notes8~1" type="checkbox" value="n8_1_yes"> Option 1
</label>
<label>
<input class="mandatory Notes8_group" name="Notes8~2" type="checkbox" value="n8_2_yes"> Option 2
</label>
<label>
<input class="mandatory Notes8_group" name="Notes8~3" type="checkbox" value="n8_3_yes"> Option 3
</label>
<button type="submit">SEND</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
you can use the function like:
Example 1: At least one:
validateMultiple('.Notes8_group', 1)
Example 2: Exactly two:
validateMultiple('.Notes8_group', 2, true)
Extra tip: If you cannot (for some reason) assign group classes, you could use the attribute selector []:
validateMultiple('[name^="Notes8~"]', 1)
which will target all by name which starts with "Notes8~", therefore all name= Notes8~1, Notes8~2 and Notes8~3 elements.