How to Display Error Messages in Lightning Web Component?
Sample Code :
SampleForm.html
=====================
<template>
<lightning-input label="FirstName"></lightning-input>
<lightning-input label="LastName"></lightning-input>
<lightning-button label="Submit" variant="brand" onclick={handleErrors}></lightning-button>
</template>
SampleForm.js
===================
import { LightningElement,track } from 'lwc';
export default class SampleForm extends LightningElement {
@track errors={
"FirstName":"Please Enter the FirstName",
"LastName":"Please Enter the LastName"
};
handleErrors(){
this.template.querySelectorAll("lightning-input").forEach(item => {
let val=item.value;
let label=item.label;
if(!val){
item.setCustomValidity(this.errors[label]);
}else{
item.setCustomValidity("");
}
item.reportValidity();
});
}
}
Follow Us