0

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.


1 Answers1

0

Setting enddate as previousEnddate replaces a value with itself, so nothing changes, therefore the framework will not modify the value of the input-field.
Anyway there is no need of previousEnddate since you set enddate only if the user selected a valid date.
You should explicitly set the attribute value of that input-field: event.currentTarget.value = this.enddate;.

By the way, you should always use const (where possibile) and let, instead of var.

handleEndDate(event){
    event.preventDefault(); 
    const startDate = new Date();
    const dateOffset = startDate.getDay() === 5 ? 3 : 1; // 3 if start date is friday
    const selectedStartDate = Date.parse(new Date(startDate.setDate(startDate.getDate() + dateOffset)));
    
    const selectedEndday = new Date(event.target.value).toDateString();

    const selectedEndDate = Date.parse(new Date(event.target.value)) ;

    let errorMessage;
    if (selectedEndday.includes('Sat') || selectedEndday.includes('Sun')) {
        errorMessage = 'Enddate cannot be on weekends';
    } else if(selectedStartDate >= selectedEndDate) {
        errorMessage = 'Enddate should be 2 days greater than start date';
    }
    
    if (errorMessage) {
        event.currentTarget.value = this.enddate; // set the previous date
        LightningAlert.open({
            message: errorMessage,
            theme: 'info', 
            label: 'Alert!'
        });
    } else {
        this.enddate = event.target.value;
    }
}
RubenDG
  • 1,365
  • 1
  • 13
  • 18