My validator error message won't disappear on one field.
I'm validating two fields to determine if the date value of the first field (startdate) is smaller than the date value of the second field (enddate). If the startdate or enddate is changed to a date beyond the enddate an error message will appear besides the enddate field.
Besides that I'm validating for the correct date format (US). When the date format is not correct an error message will appear besides the changed field.
I re-created the situation: https://jsfiddle.net/fzbqqsfb/4/
HTML:
<form>
<label>field one:
<input name="one" type="text" class="date startdate before-enddate">
</label>
<label>field two:
<input name="two" type="text" class="date enddate after-startdate">
</label>
</form>
Javascript:
$.validator.addMethod("beforeEndDate", function(value, element, params) {
var validator = $(element).closest('form').validate();
validator.element(params);
return true;
}, "starting date must be before end date");
$.validator.addMethod("afterStartDate", function() {
return Date.parse($('.startdate').val()) < Date.parse($('.enddate').val());
}, "end date must be after start date");
$.validator.addClassRules({
'before-enddate': {
beforeEndDate: '.enddate'
},
'after-startdate': {
afterStartDate: '.startdate'
}
});
$('form').validate();
When the date format is not correct on the startdate field I'll get the expected error message "Please enter a valid date." but when I correct this to a valid date the error message won't disappear.
I'm clearly doing something wrong but after two days I'm unable to find the problem. Perhaps it's a problem with validor.element(el) construction?
workaround (19-07-2016)
I've found an acceptable solution / workaround for my problem by moving a validation trigger outside the validation itself. It will validate the complete form, adding and removing the correct error messages to all fields.
$.validator.addMethod("afterStartDate", function() {
return Date.parse($('.startdate').val()) < Date.parse($('.enddate').val());
}, "end date must be after start date");
$.validator.addClassRules({
'after-startdate': {
afterStartDate: '.startdate'
}
});
$('form').validate();
$('.startdate').on('change', function() {
$(this).closest('form').valid();
});