Lightning Web Component Custom Validations
Published in
1 min readOct 11, 2021
It sometimes happens that users input bad data when working with input values. In this case, we need to validate the data and show the user a custom message to inform them of the error.
This is the way to go setCustomValidity() and reportValidity() methods to validate and display custom errors.
<template>
<lightning-card title="Custom Validations In Lightning Web Components">
<lightning-input class="nameCmp" label="Enter Name" type="string"></lightning-input>
<lightning-input class="dateCmp" label="Enter Date" type="date"></lightning-input><br/><br/>
<lightning-button class="slds-align_absolute-center" label="Search" variant="brand" onclick={testTheData}></lightning-button>
</lightning-card>
</template>import { LightningElement, track } from 'lwc';
export default class DemoApp extends LightningElement {
testTheData() {
let searchCmp = this.template.querySelector(".nameCmp");
let dateCmp = this.template.querySelector(".dateCmp");
let searchvalue = searchCmp.value;
let dtValue = dateCmp.value;
if (!searchvalue) {
searchCmp.setCustomValidity("Name value is required");
} else {
searchCmp.setCustomValidity("");
}
searchCmp.reportValidity();
if (!dtValue) {
dateCmp.setCustomValidity("Date value is required");
} else {
dateCmp.setCustomValidity("");
}
dateCmp.reportValidity();
}
}