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

4 comments:

  1. please provide the create and edit form with custom validation

    ReplyDelete
  2. its giving error 'setCustomValidity' is not a function, what could be the reason ?

    ReplyDelete
  3. How. does it work with lightning-input type="date"

    ReplyDelete