Friday, April 17, 2020

Handle Custom Validations in Lightning Web Components(lwc)

When we working with input values some times users enter the bad data, In this situation we need to validate the data and show the custom error message to the user to correct the data.

Use the setCustomValidity() and reportValidity() methods to validate and dsiplay custom error message.

Demo:
HTML Code
<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={searchTheData}></lightning-button>
    </lightning-card>
</template>

Javascript Code
import { LightningElement, track } from 'lwc';

export default class DemoApp extends LightningElement {

    searchTheData() {
        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(""); // clear previous value
        }
        searchCmp.reportValidity();

        if (!dtValue) {
            dateCmp.setCustomValidity("Date value is required");
        } else {
            dateCmp.setCustomValidity(""); // clear previous value
        }
        dateCmp.reportValidity();
    }
}

Output

No comments:

Post a Comment