LWC component Date Field should not change if validation fails onchange event.
I have an LWC component lightning-record-edit-form with startDate and EndDate input fields. Start date is always currentdate(read-only) and enddate an editable field with default value auto-populated. When the user changes the enddate, it should do a validation that selected enddate should be 2 days greater than startdate excluding Saturday & Sunday. If the validation fails then on change should stop or should show the previous value.
This is my sample code: Html part
<lightning-record-edit-form>
<lightning-input-field field-name="Start_Date_Time__c" required="true" value={currentDate} readonly="true"></lightning-input-field>
<lightning-input-field data-name="enddatefield" field-name="End_Date_Time__c" required="true" value={enddate} onchange={handleEndDate}></lightning-input-field>
<lightning-record-edit-form>
JS part
currentDate;
enddate;
previousEnddate;
connectedCallback(){
this.currentDate = new Date().toISOString();
var startDate = new Date();
var lastdate;
let noOfDaysToAdd = 2, count = 0;
while(count < noOfDaysToAdd){
lastdate = new Date(startDate.setDate(startDate.getDate() + 1));
if(lastdate.getDay() != 0 && lastdate.getDay() != 6){
count++;
}
}
this.enddate = lastdate.toISOString();
}
handleEndDate(event){
event.preventDefault();
var startDate = new Date();
this.previousEnddate = this.enddate;
let selectedStartDate;
if(startDate.getDay()==5){// start date is friday
selectedStartDate = Date.parse(new Date(startDate.setDate(startDate.getDate()+3)));
}else{
selectedStartDate = Date.parse(new Date(startDate.setDate(startDate.getDate()+1)));
}
let selectedEndday = new Date(event.target.value).toDateString();
let selectedEndDate = Date.parse(new Date(event.target.value)) ;
if(selectedEndday.includes('Sat') || selectedEndday.includes('Sun')){
this.enddate = this.previousEnddate;
LightningAlert.open({
message: 'Enddate cannot be on weekends',
theme: 'info',
label: 'Alert!'
}).then(function(){
});
}else if(selectedStartDate >= selectedEndDate){
this.enddate = this.previousEnddate;
LightningAlert.open({
message: 'Enddate should be 2 days greater than start date',
theme: 'info',
label: 'Alert!'
}).then(function(){
});
}else{
this.enddate =event.target.value;
}
}
When the user selectes saturday or sunday, I could see the alert message but still the newly selected date is showing in the field. It is not showing the old value.