Reputation: 1
I have a text box and I want to check whether the user entered value is equal to "Jhon" or some name. I tried with EqualTo validation rule but it doesnt work.
$('#home').validate({
rules: {
name: {
required: true,
equalTo: 'Jhon'
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
Upvotes: 0
Views: 10304
Reputation: 98738
Three problems with your code:
1) The equalTo
rule is for matching one field to another field, not a string. To match a string, you'll need to write a custom method using the addMethod
method, which I'll show below.
2) You've incorrectly placed highlight
and success
inside of the rules
option. Only field names and rule declarations go inside of rules
. The highlight
and success
callback functions are siblings of rules
, not descendants. You also incorrectly placed a );
inside of .validate()
.
3) You're using the highlight
callback function but you're not using its complementary function, unhighlight
. Whatever you set with highlight
, should only be removed using unhighlight
.
This is your corrected code below...
$(document).ready(function () {
$.validator.addMethod("customrule", function(value, element, param) {
return this.optional(element) || value === param;
}, "You must enter {0}");
$('#home').validate({
rules: {
name: {
required: true,
customrule: 'John'
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
unhighlight: function (element) {
$(element).closest('.control-group').removeClass('error').addClass('success');
},
success: function (element) {
element.text('OK!').addClass('valid');
}
});
});
Working DEMO: http://jsfiddle.net/VYceT/
Upvotes: 5