jQuery validation: Indicate that at least one element in a group is required

I had a need today to indicate that at least one of a set of input fields was required. I was hoping there was a direct way to do this in the jQuery validation plugin; while the method isn't quite as straightforward as I was wishing for, it's still fairly simple. To start with, I put class="required_group" on each of the elements in the group. Then, I added a custom validation method:

jQuery.validator.addMethod('required_group', function(val, el) {
        var $module = $(el).parents('div.panel');
        return $module.find('.required_group:filled').length;
});
... a custom class rule to take advantage of the new method:
jQuery.validator.addClassRules('required_group', {
        'required_group' : true
});
... and finally a custom message for the new method:
jQuery.validator.messages.required_group = 'Please fill out at least one of these fields.';
What I'd love to see is a way to specify a dependent group without using a custom class rule, but I'm not sure what this would look like, as all validation rules are either keyed off an element's class or the presence of the element's name in the rules object. Thoughts? I'm open to the possibility that there's a far better way to solve this --

Loading mentions Retweet

Posted 1 year ago

19 comments

Apr 16, 2009
Jörn Zaefferer said...
Its hard to produce a more generic solution to the problem here. But can simplify the code a bit, this should be enough:

jQuery.validator.addMethod('required_group', function(val, el) {
var $module = $(el).parents('div.panel');
return $module.find('.required_group:filled').length;
}, 'Please fill out at least one of these fields.');

That is, pass the default message as the third argument to addMethod. And addClassRules isn't necessary at all, you can use the method name as a class once the method was added.

Apr 23, 2009
Gary said...
Merci pour cette petite fonction bien utile.
Thanks for that useful function !
Apr 24, 2009
Vivian Goodrich said...
I want to do something similar and was hoping for some help. I have 2 fields (firstName and lastName) and I want them both to be required. Is there a way to use the validator to give an error if either or both is empty? In other words, instead of "Indicate that at least one element in a group is required" I want to "Indicate all elements in a group are required".
Apr 24, 2009
Rebecca said...
@Vivian You may want to look into the errorPlacement setting. I've used this when I want to display a single error for a group of related fields.
Apr 24, 2009
Vivian Goodrich said...
Rebecca,
Thank you for replying so quickly. I played with doing that, and it works well for the errors, but I can't figure out how to mark the success when they are both correct.

Right now I have:
errorPlacement : function(error, element) {
if (element.attr("name") == "firstName" || element.attr("name") == "lastName") {
$("#lastNameError").html("  Please enter your first and last names.");
} else {
error.appendTo(element.parent("div").next("div"));
}
},
success : function(label) {
label.html(" ").addClass("success");
},

I made an exception for the 2 fields to treat the error differently. But wondering how to mark success only if they are both correct. And I'm not sure if that's the best way to handle if test in the errorPlacement.

Jun 25, 2009
Justin said...
I'm working on something similar, anyone have an idea on how to get this working for checkboxes? I'm trying to require at least one checkbox (altogether, not each) checked from two different groups of checkboxes. Each group has a different name so I haven't been able to use the built in checkbox group.
Jul 09, 2009
Michael said...
@Justin: Try to select an element that wraps around both groups. This is what I have - it should work for you!

$.validator.addMethod('required_group', function(value, element) {
var $module = $(element).parents('form');
return $module.find('input.form-checkbox:checked').length;
});

$.validator.addClassRules('form-checkbox', {
'required_group' : true
});

Jul 31, 2009
kab said...
I tried the above for my checkboxes, but it is giving me 8 error messages rather thanjust one for the group. Any ideas? Thanks
Aug 19, 2009
Nathan Long said...
This is great! I've cited you as I worked on my own version. I have added a couple of improvements (at least for my purposes):

1) To let you pass in a selector for the group of fields, and therefore use more than one group per page.
2) To hide error messages on all fields in the group as soon as one of them validates.

I'm asking for feedback on my code on StackOverFlow, in case anyone is interested.

Oct 12, 2009
olivier said...
Hello,
thank you but can you post a working example because I cant make this code work.
heres my code:
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
nom: "required",
prenom: "required",
ville: "required",
cp: "required"
}
});
});

jQuery.validator.addMethod("required_group", function(val, el) {
var $module = $(el).parents('div.panel');
return $module.find('.required_group:filled').length;
}, "at least a phone number.");

and in my form #signupform

Telephone:




Mobile:



error message appears but no remove when I fill one of the two imput.
Thanks for help :)

Oct 12, 2009
olivier said...
in my form I just add class="required_group" in my input
thank you
Nov 24, 2009
Felix said...
Hi,
i need to check if at least one input field in group is filled which works fine and then i need to check if the entered value is numeric and greather than 0.

Any Idea?

Thanks Felix

Dec 15, 2009
Mag said...
Hi Rebecca,

Have you come across a way to validate a group of fields as one via JQuery "out-of-the-box" validation?

I have a bank sort code to validate which is 3 inputs, but I only want one error message to appear if any of them are incorrect, and not 3 e.g.

"Please enter a valid sort code"

Cheers.

Feb 10, 2010
Mark Jones said...
Thanks for posting your code. I am experiencing a problem just like comment #10. I can get the code to work no problem on the page. If neither of my two checkboxes are checked then the error message appears beside each box. However, once I click one of the boxes the error does not disappear (not even after resubmission of the form).

Any help would be greatly appreciated.

Feb 20, 2010
Armando Borge said...
Ok...

If you need indicate that at least one of a set of input fields is required you can do it direct whit the jquery validate plugin:

HTML:
When you set your checkbox group, use the same name for each input and use [] at the end of the names.

Javascript:
use quotes ('field[]') in rules declaration for your input group

$("#form").validate(
{
rules: { 'field[]':{ required:true, minlength:1 }
}

Note: PHP convert the input group in array... well, I hope this help...

Mar 24, 2010
Clintar said...
I had the same issue, but I figured it was because of the explicit .parents('div.panel') which I didn't have my form entries descendants of. I just took them out and just had .parents() and it worked. I then just figured out something that they were both under and had it use that instead. I assume this is for efficiency? Thanks for the page. After reading the comments again, it looks like Micheal explained what needed to be done, too. Hope that helps someone trying to use this. Thanks Rebecca!
Mar 26, 2010
David said...
For some reason, I can't get jQuery.validator to work in Wordpress. When I add any call to this, the jQuery validation plugin stops working, as if it's not even on the page.

So I found this workaround that avoids adding the custom validation method. (Note I'm using "jQuery" spelled out rather than "$" because it's in Wordpress, which uses the $ alias for something else.) The code below passes validation of each field if at least one of the fields is not empty. If both fields are empty, validation fails.

jQuery(document).ready(function(){
jQuery("#myForm").validate({
rules: {
field1name: {
required: function(element) {
return (jQuery("#field2ID").val() == "" );
}
}
field2name: {
required: function(element) {
return (jQuery("#field1ID").val() == "" );
}
}
}
});
});

May 13, 2010
Kane said...
Hi, great work. I have one question, I only need the requird_group to validate if another box is checked. where do I insert the required: "#trial:checked" part? Ive tried putting it everywhere to no avail. Also, its requiring each member of the group, not just one of the group (3). Any advice is appreciated.
thanks!
Jun 27, 2010
jQuery, how do I indicate one checkbox in group is required | The Largest Forum Archive said...
[...] Solve One Solve Two [...]

Leave a comment...