Reputation: 882
I have two email fields: email1 & email2. I want both of them to be distinct. For some reasons, I am keeping email1 as readonly and email2 as editable. Below is my code-
My custom validator is as follows -
$.validator.addMethod("email_not_same", function(value, element) {
return $('#email1').val() != $('#email2').val();
}, "Both emails should not be same");
My rules are as follows -
email1: {
required: true,
email: true,
},
email2: {
email: true,
email_not_same: true,
},
My html code is as follows:
<div class="form-group col-md-12">
<label><strong>Emails : </strong></label>
</div>
<div class="form-group col-md-6">
<input class="form-control" name="email1" placeholder="Email 1" type="email">
</div>
<div class="form-group col-md-6">
<input class="form-control" name="email2" placeholder="Email 2" type="email">
</div>
When I enter both email addresses same; it shows the message according to my rule. However, after that when I change my email2, it still shows the error message. Please help.
Upvotes: 2
Views: 56
Reputation: 15154
As the other both answers advise, you are looking for the Id
in your selector. you could add the Id
or change your selectors to look up the name
like so:-
$.validator.addMethod("email_not_same", function(value, element) {
return $('[name="email1"]').val() != $('[name="email2"]').val();
}, "Both emails should not be same");
Upvotes: 1
Reputation: 167172
You are missing id
attribute for the emails:
<input class="form-control" id="email1" name="email1" placeholder="Email 1" type="email" />
<input class="form-control" id="email2" name="email2" placeholder="Email 2" type="email" />
But you are using them here:
return $('#email1').val() != $('#email2').val();
Upvotes: 1
Reputation: 115
You are using jQuery selector for ID (#email1 and #email2) but in HTML there is no id attribute specified but "name". Add id attribute and try again.
<input class="form-control" id="email1" name="email1" placeholder="Email 1" type="email">
<input class="form-control" id="email2" name="email2" placeholder="Email 2" type="email">
Upvotes: 2