Lightning Web Component Custom Validations

LWC custom Validation

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();
}
}
Custom Validation Output

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ranbir Kumar Das

Ranbir Kumar Das

260 Followers

I M Believer, Helper, Chaser, Thinker, Rich, Explorer, Prayer, Boss, Freedom, Fearless, Investor, Faith, Creator, trillionaire, CSM, Salesforce certified