How to add a Not Equal To rule in jQuery.validation
Solution 1:
You could use a custom method, something like this:
jQuery.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value != param;
}, "Please specify a different (non-default) value");
Then use it like this:
$("form").validate({
rules: {
nameField: { notEqual: "Your Name" }
}
});
Adding it as a rule like this makes it more extensible, so you can use it to compare against the default value in other fields.
Solution 2:
Nick's answer fits the bill. I needed to compare two fields on the form and make sure they were not equal. I modified it just a bit.
jQuery.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value != $(param).val();
}, "This has to be different...");
$("#cform").validate(
{
rules: {
referringsales: { required: false, notEqual: "#salesperson" }
}
});
Edited to answer comment:
If you have more than one set of dropdowns to compare, the method also works with that case.
jQuery.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value != $(param).val();
}, "This has to be different...");
$("#cform").validate(
{
rules: {
referringsales: { required: false, notEqual: "#salesperson" }
DropDown2: { required: false, notEqual: "#SecondBase" }
}
});
If the question is regarding comparing referringsales against 2 different bases (say #initialContact and #salesperson), then simply add that rule to the list.
referringsales: { required: false, notEqual: "#salesperson", notEqual: "#initialContact" }
Solution 3:
I propose a multi-valued function...
jQuery.validator.addMethod("notEqualTo",
function(value, element, param) {
var notEqual = true;
value = $.trim(value);
for (i = 0; i < param.length; i++) {
if (value == $.trim($(param[i]).val())) { notEqual = false; }
}
return this.optional(element) || notEqual;
},
"Please enter a diferent value."
);
And I call it...
$("#abm-form").validate({
debug: true,
rules: {
password1: {
required: true,
minlength: 10,
notEqualTo: ['#lastname', '#firstname', '#email']
},
password2: {
equalTo: '#password1'
}
}
});
This works for me!