jQuery Validate - require at least one field in a group to be filled jQuery Validate - require at least one field in a group to be filled jquery jquery

jQuery Validate - require at least one field in a group to be filled


That's an excellent solution Nathan. Thanks a lot.

Here's a way making the above code work, in case someone runs into trouble integrating it, like I did:

Code inside the additional-methods.js file:

jQuery.validator.addMethod("require_from_group", function(value, element, options) {...// Nathan's code without any changes}, jQuery.format("Please fill out at least {0} of these fields."));// "filone" is the class we will use for the input elements at this examplejQuery.validator.addClassRules("fillone", {    require_from_group: [1,".fillone"]});

Code inside the html file:

<input id="field1" class="fillone" type="text" value="" name="field1" /><input id="field2" class="fillone" type="text" value="" name="field2" /><input id="field3" class="fillone" type="text" value="" name="field3" /><input id="field4" class="fillone" type="text" value="" name="field4" />

Don't forget to include additional-methods.js file!


Nice solution. However, I had the problem of other required rules not working. Executing .valid() against the form fixed this issue for me.

if(!$(element).data('being_validated')) {  var fields = $(selector, element.form);  fields.data('being_validated', true);   $(element.form).valid();  fields.data('being_validated', false);}


Thanks sean. That fixed the issue I had with the code ignoring other rules.

I also made a few changes so that 'Please fill out at least 1 field ..' message shows in a separate div instead of after all every field.

put in form validate script

showErrors: function(errorMap, errorList){            $("#form_error").html("Please fill out at least 1 field before submitting.");            this.defaultShowErrors();        },

add this somewhere in the page

<div class="error" id="form_error"></div>

add to the require_from_group method addMethod function

 if(validOrNot){    $("#form_error").hide();}else{    $("#form_error").show();}......}, jQuery.format("  (!)"));