'how to get rid of errorClass in start date if end date is correct validate jquery
I have start date and end date, HTML below:
<div class="wrapper">
<div class="form-group">
<label class="col-form-label col-sm-3 required">Start Date</label>
<div class="col-sm-9">
<input name="startDate" type="text" class="validation-invalid-label" value="03-10-2024">
</div>
</div>
<div class="form-group">
<label class="col-form-label col-sm-3 required">End Date</label>
<div class="col-sm-9">
<input name="endDate" type="text" class="valid" value="02-10-2025">
</div>
</div>
</div>
I set start date, for example, 03-10-2022 and end date 02-10-2023. Then I focus on start date and set it to 03-10-2024 which is not correct by validation(text becomes red). To solve it I set end date to 02-10-2025. End date becomes black as it must be but start date stays red(it becomes black only when I focus on it).My code below:
$(selector).validate({
rules: {
startDate: {
required: true
},
endDate: {
required: true,
dependsOnDate: {
comparisonDate: `input[name="startDate"]`,
method: 'isAfter'
}
}
},
messages: {
startDate: {
required: "Invalid date",
},
endDate: {
required: "Invalid date",
dependsOnDate: "Invalid date"
},
},
errorClass: 'validation-invalid-label',
successClass: 'validation-valid-label',
highlight: function(element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
$(element).parents('.wrapper').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
if (!_.some(_.keys(this.invalid), key => !_.isUndefined(this.invalid[key]) && this.invalid[key]!== false)) {
$(element).removeClass(errorClass).addClass(validClass);
$(element).parents('.wrapper').removeClass('has-error');
}
},
});
So I need to remove errorClass from start date if end date becomes correct. My custom method:
$.validator.addMethod("dependsOnDate", function(value, element, params) {
const givenDate = moment(value);
const comparisonDate = moment($(params.comparisonDate).val())
return givenDate[params.method](comparisonDate);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
