CustomValidation in LWC

 Lwc provides custom validity to validate the input fields with custom validation rules. We can show the error message if the field doesn’t meet the input format. The error message would be shown on the particular field which gets a validation error.

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

customValidity.html

<template>

        <lightning-card title=”Custom Validations In Lightning Web  

                                                           Components”>

          <div style=”justify-content:center;display:flex”>

             <div>

              <lightning-input class=”nameCmp” label=”Enter Name” 

                type=”string” style=”width:fit-content”>

        </lightning-input>

              <lightning-input class=”dateCmp” 

              label=”Enter Date” 

                    type=”date”             

                    style=”width:fit-content”>

              </lightning-input><br/><br/>

              <lightning-button 

                   class=”slds-align_absolute-center” 

                   label=”Search” variant=”brand” 

                   onclick={testTheData}>

              </lightning-button>

            </div>

   </div>

     </lightning-card>

  </template>

customValidity.js

   import { LightningElement } from ‘lwc’;

   export default class CustomValidity 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();

    }

  }

Output: