Dynamic validation in Lightning Webcomponent



customValidation.html
=====================
<template>
   <lightning-input type="text" label="FirstName">
   </lightning-input>
   <lightning-input type="text" label="LastName" >
   </lightning-input>
   <lightning-button label="validate"  onclick={handleValidate}>
   </lightning-button>
</template>

customValidation.Js
===================
import { LightningElement, } from 'lwc';
export default class CustomValidation extends LightningElement {
    handleValidate(event){
        let customErrorMessage="Please Enter the";
        this.template.querySelectorAll("lightning-input").forEach(item => {
            let value=item.value;
            let currentLabel=item.label;
            if(!value){
                item.setCustomValidity(customErrorMessage+' '+currentLabel);
            }
else{
                item.setCustomValidity("");
            }
            item.reportValidity();
});
    }
}

Comments