I have been using the excellent jQuery Validation plugin in my latest project. It provides all the basic rules that you will need for validating your form. However, I had a form with 2 username fields on it and the requirement was that they should not be equal to each other. I guess this is not a very common scenario, which is why the “notEqualTo” rule was not included in the original ruleset of the plugin. There is a “equalTo” rule already, though.
However, it was pretty easy to write this rule and I am just posting it here incase someone might need it. In my additional-methods.js file, I just added this piece of code :-
jQuery.validator.addMethod("notEqualTo", function(value, element, param) {
return this.optional(element) || value != $(param).val();
}, "This has to be different...");
And then in your rules definition, all you have to do is this :-
var validator = $("#signupform").validate({
rules: {
username: {
required: true,
minlength: 6,
maxlength:16,
remote:'checkUserName',
nowhitespace:true,
alphanumeric:true,
notEqualTo:'#otherusername'
},
messages: {
username: {
required: "Enter a username",
minlength: jQuery.format("Enter at least {0} characters"),
remote: 'Username not available',
alphanumeric: 'Letters, Numbers and Underscores Only.',
notEqualTo: 'Profile and Customer Usernames cant be same'
}
});
Pretty easy to do and a big than you to the great plugin.
#1 by Biran Maharjan on May 24, 2010 - 5:16 am
Quote
I had used the method you had given in (http://www.anujgakhar.com/2009/08/26/jquery-validation-plugin-and-notequalto-rule/). this works only for 2 fields. But in my form there are 8 email fields which should not be same from other. How can i make your code workable for multiple fields.
#2 by Anuj Gakhar on May 24, 2010 - 11:14 am
Quote
I guess you are going to have to pass an array of all the “other” 7 emails to the validator and then compare with each of them. Unless there is a plugin already written for such a thing, I cant see any other way of doing this.
Pingback: jQuery Validator Plugin and notEqualTo Rule (with Multiple Fields) | Anuj Gakhar's Blog
#3 by Anuj Gakhar on May 24, 2010 - 2:12 pm
Quote
I have written up a blog entry for this. Hope this helps.
http://www.anujgakhar.com/2010/05/24/jquery-validator-plugin-and-notequalto-rule-with-multiple-fields/
#4 by Haneefa Abdulla on July 29, 2010 - 7:47 am
Quote
It is very helpful that it reminds me to add more plugins like this
#5 by Fobin on September 3, 2010 - 8:52 am
Quote
Should this work also in jQuery 1.4.2 and Validator 1.7?
I’ve tried to put it in use at my site http://www.muistiohjelma.fi but it doesn’t seem to validate this:
rules: {
paikkakunta: {
required: true,
notEqualTo:’Paikkakunta’,
},
}
Can you use string there like have in this?