Reputation: 1997
I have a function which compares two fields.
$.validator.addMethod("validatormethod", function (value, element) {
return $('#Field1').val() > $('#Field2').val()
}, "Test");
The form is dynamic and hence the form is validated using each
:
$('.validateclass').each(function () {
$(this).rules('add', {
validatormethod: true,
messages: {validatormethod: "Test" }
})
});
$('.validateclass2').each(function () {
$(this).rules('add', {
required: true,
messages: {required: "This field is required" }
})
});
$('#myForm').valid();
Now my problem is the message Test
appears as soon as the page loads. It should appear only after the field is compared. I know it is due the the line $('#formSaveComponent').valid();
. But I want the required message to appear when the page loads. Is there some way I can get this done using jQuery Validate plugin.
Upvotes: 0
Views: 565
Reputation: 98758
Quote OP:
"Now my problem is the message Test appears as soon as the page loads. It should appear only after the field is compared."
You've written your custom method as if the fields are required
... that is why you're getting the error message immediately and while the fields are still empty.
As long as these fields are not required
, you would need to add this.optional( element ) ||
to your custom method as follows...
$.validator.addMethod("validatormethod", function (value, element) {
return this.optional( element ) || $('#Field1').val() > $('#Field2').val()
}, "Test");
Now the custom method will not fire unless something is entered into the relevant fields.
EDIT 1
Although I have no idea why, in your jsFiddle, you are comparing txtLastName
to txtFirstName
with a >
comparison operator... exactly how could one name be "greater than" the other?
EDIT 2
Your jsFiddle is broken because...
You are targeting fields by id
, however your fields only contain a name
and no id
.
Change $('#fieldname')
into $('[name="fieldname"]')
to target them by name
.
You are comparing two strings with a comparision operator, which will always fail because strings are not numbers. You need parseInt()
to convert the string into an integer in order to compare them...
parseInt($('[name="fieldname"]').val())
DEMO: http://jsfiddle.net/h4bf10vt/3/
Upvotes: 1