I'm using the jQuery Validation plugin on my forms. I have some groups of fields that are optional, but need to be either "all or nothing" - if you fill one input in a group, you must fill all of them.
For example, imagine the user can input one location - street, city, state, and zip - or multiple locations. You don't have to enter a second location, but if you do, it's not OK to just give the city; I need the state and zip for that one too.
To solve this problem, I wrote a custom rule - really just a tiny tweak of my previous rule, require_from_group
. This one is called skip_or_fill_minimum
. Here's how you'd use it:
var validationrules = {
rules: {
location2address: {
skip_or_fill_minimum: [4,'.location2']
}
//This input will validate if all 4 `.location2` inputs are filled,
//or if all of them are left blank
}
var validator = $("#formtovalidate").validate(validationrules);
Here's the code for the custom rule:
jQuery.validator.addMethod("skip_or_fill_minimum", function(value, element, options) {
numberRequired = options[0];
selector = options[1];
//Look for our selector within the parent form
var numberFilled = $(selector, element.form).filter(function() {
// Each field is kept if it has a value
return $(this).val();
}).length;
var valid;
(numberFilled >= numberRequired || numberFilled == 0) ? valid = true: valid = false;
//The elegent part - this element needs to check the others that match the
//selector, but we don't want to set off a feedback loop where all the
//elements check all the others which check all the others which
//check all the others...
//So instead we
// 1) Flag all matching elements as 'currently being validated'
// using jQuery's .data()
// 2) Re-run validation on each of them. Since the others are now
// flagged as being in the process, they will skip this section,
// and therefore won't turn around and validate everything else
// 3) Once that's done, we remove the 'currently being validated' flag
// from all the elements
if(!$(element).data('being_validated')) {
var fields = $(selector, element.form);
//.validate() means "validate using all applicable rules" (which includes this one)
fields.data('being_validated', true).validate();
fields.data('being_validated', false);
}
return valid;
// {0} below is the 0th item in the options field
}, jQuery.format("Please either skip these fields or fill at least {0} of them."));
I'm primarily posting this so that others who search the web for a solution will find it. Still - does anyone see a way to improve this?