[SalesForce] Validation onclick button is not working in LWC

I'm currently getting error "[b.reportValidity is not a function]"

Below is the code:

HTML:

<lightning-combobox required name="duration" label="Select Duration" value={durationValue} placeholder="Select Duration" options={durationOptions}></lightning-combobox>
<lightning-button variant="brand" label="Generate" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>

JS:

handleClick(event) {
    const allValid = [this.template.querySelectorAll('lightning-combobox')]
        .reduce((validSoFar, inputCmp) = > {
            inputCmp.reportValidity();
            return validSoFar && inputCmp.checkValidity();
        }, true);
    if (allValid) {
        alert('All form entries look valid. Ready to submit!');
    } else {
        alert('Please update the invalid form entries and try again.');
    }
}

Could anyone tell me where I'm doing wrong?

Best Answer

You need to change code like below and it will work. There is small change in code at ...this.template.querySelectorAll

handleClick(event) {

    const allValid = [...this.template.querySelectorAll('lightning-combobox')]
        .reduce((validSoFar, inputCmp) => {
            inputCmp.reportValidity();
            return validSoFar && inputCmp.checkValidity();
        }, true);
    if (allValid) {
        alert('All form entries look valid. Ready to submit!');
    } else {
        alert('Please update the invalid form entries and try again.');
    }
}
Related Topic