Reputation: 1380
I have a scenario when I have 3 dropdowns and need to implement two validations over them but as a group.
1) Out of 3, 2 dropdowns should have value other than "No". This is similar to required validation. Instead of check for blank will check for "No".
2) No 2 dropdowns can have same value.
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
var fields = $(selector, element.form);
var filled_fields = fields.filter(function() {
// it's more clear to compare with empty string
return $(this).val() != "No";
});
var empty_fields = fields.not(filled_fields);
// we will mark only first empty field as invalid
if (filled_fields.length < numberRequired){ //&& empty_fields[0] == element) {
return false;
}
return true;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
jQuery.validator.addMethod("notEqualToGroup", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(selector).not(element);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function(){
thisVal = $(this).val();
if(thisVal == valueToCompare){
matchesFound++;
}
});
if (matchesFound >= numberRequired){ //&& elems[0] != element) {
return false;
}
return true;
}, jQuery.format("No two fields can have same value."));
One of the scenarios has failed i.e. when select1 and select2 are not "No" but still have same value no msg is displayed.
Can someone please suggest whats missing. Thanks
Upvotes: 0
Views: 278
Reputation: 98738
Upgrade the plugin from the nearly 7-year-old version 1.7 to the latest which is 1.15.
Replace the outdated version of require_from_group
with the latest one from version 1.15.
Replace jQuery.format("No two fields can have same value.")
with $.validator.format("No two...
You'll find that this updated version works a bit more predictably.
EDIT:
You also need a complete rewrite on your notEqualToGroup
rule:
$.validator.addMethod("notEqualToGroup", function(value, element, options) {
var isvalid = true,
values = [],
temp = [];
// put all values into an array
$(options).each(function() {
values.push($(this).val());
});
// check array for duplicates
$.each(values, function(key, val) {
if ($.inArray(val, temp) === -1) {
temp.push(val);
} else {
isvalid = false; // duplicate found
}
});
return isvalid;
}, $.validator.format("No two fields can have same value."));
Essentially, put all three values into an array and check for duplicates.
....
select1: {
require_from_group: [2, ".at_least_one"],
notEqualToGroup: ".at_least_one"
},
....
DEMO: jsfiddle.net/nu4dcstv/
Upvotes: 1