I must admit that this is a hack and needs to be adapted to your needs. This is what I came up with, and there may be better options.
Layout Example:
<form action="" id="theForm"> <fieldset> <input type="radio" name="sex" value="male" id="male" class="requiredCheckbox" /> <label for="male">Male</label><br /> <input type="radio" name="sex" value="female" id="female" /> <label for="female">Female</label><br/> <input type="radio" name="sex" value="unknown" id="unknown" /> <label for="unknown">Unknown</label> </fieldset> <input type="button" id="validate" value="Validate" /> </form> β
Javascript with a custom validation method and a small hacker:
$.validator.addMethod('requiredCheckbox', function (val, elt) { var valid = false; $('input[name=' + $(elt).attr('name') + ']:radio').each(function(inx, elt) { if (elt.checked === true) { valid = true; return; } }); return valid; }, 'Select at least one checkbox'); var options = { errorPlacement: function(error, elt) { $(elt).before(error); }, errorElement: 'div' }; var validator = $('#theForm').validate(options ); $('#validate').click(function() { $('#theForm').valid(); });β
Here's a JSFiddle with a working sample: http://jsfiddle.net/9DRcz/
Fun problem to develop :-)
source share