[SalesForce] Clearing validation errors on clicking clear filters icon not working on LWC lightning-input

The validation errors are cleared only on the second click of the button. But i need this to be working on the first click. Kindly help.
My current code is as follows :

HTML CODE :

<div class="slds-size_3-of-4 slds-grid">
     <lightning-input type="date" title="Enter the start date from which you need to filter the records" name="startdate"
            class="startdate slds-col slds-size_1-of-4 slds-m-left_medium slds-align_absolute-center" label="Start Date"
        placeholder="Start Date" value={start_date} onselect={handleFilter} onchange={handleFilter} max={maxStartDate}>
     </lightning-input>
     <lightning-input type="date" title="Enter the end date till which you need to filter the records" name="enddate"
            class="enddate slds-col slds-size_1-of-4 slds-m-left_medium slds-align_absolute-center" label="End Date"
        placeholder="End Date" value={end_date} onselect={handleFilter}onchange={handleFilter} max={maxdate}>
     </lightning-input>
     <div class="slds-col slds-size_1-of-4 slds-m-left_medium slds-align_absolute-center"></div>
     <div class="slds-col slds-size_1-of-4 slds-m-left_medium slds-align_absolute-center">
         <lightning-button variant="brand-outline" label="Clear Filters" title="Clear All Filters" onclick={handleClear}
               class="slds-m-left_x-medium slds-align_absolute-center slds-grid_vertical-align-center clear-button"
               style="margin-top: 5px;">
         </lightning-button>
     </div>
</div>

JS CODE :


    handleClear() {
        this.template.querySelector('form').reset();
        this.start_date = null;
        this.end_date = null;
        this.template.querySelectorAll('lightning-input').forEach(element => {
            element.reportValidity();
            element.setCustomValidity('');
        });
    }

Image :
enter image description here

The error goes away only on clicking the clear filter button twice.
Kindly help and let me know that what is being done wrongly or what could be added to it.

Best Answer

The errors don't get cleared in the first click because the element's values are still intact eventhough you are setting start_date and end_date to null. A workaround would be to put a delay and wait for the input values to change and report validity after the function finishes.

handleClear() {
    this.start_date = null;
    this.end_date = null;
    window.setTimeout(() => {
        this.template.querySelectorAll('lightning-input').forEach((element) => { 
            element.reportValidity();
        });
    }, 10)};
}
Related Topic