Custom validation in Lightning Web Component

by Rijwan Mohmmed
0 comment
custom-validation-in-lightning-web-component-techdicer

Hello friends, In this post, we’re going to learn how we can apply Custom validation in Lightning Web Component(LWC). We’re going to create a simple form and then we’ll apply validation to each field one by one.

Also check this: Set default fields values on create record LWC Salesforce

It is common for users to enter incorrect data when working with input values, so we need to validate the data and display a custom error message for the user.

Key Highlights :

  1. Create a simple form.
  2. Validate each field with a custom error message.
  3. Show user-like error messages.
  4. Use the setCustomValidity() and reportValidity() methods to validate and display custom error message.

Code :

Customvalidationlwc.HTML :

<template>
	<lightning-card title="Custom validation in Lightning Web Component" icon-name="standard:contact">
		<div class="slds-var-p-around_small">
			<lightning-input class="nameCls" label="Enter Name" type="text" required></lightning-input>
			<lightning-input class="emailCls" label="Enter Email" type="email" required></lightning-input>
			<lightning-input class="dateCls" label="Enter Date" type="date" required></lightning-input><br/><br/>
			<lightning-button class="slds-align_absolute-center" label="Validate" variant="brand"
				onclick={handleValidation}></lightning-button>
		</div>
	</lightning-card>
</template>

Customvalidationlwc.JS :

import { LightningElement, track } from 'lwc';

export default class Customvalidationlwc extends LightningElement {

    handleValidation() {
        let nameCmp = this.template.querySelector(".nameCls");
        let dateCmp = this.template.querySelector(".dateCls");
        let emailCmp = this.template.querySelector(".emailCls");
       
        if (!nameCmp.value) {
            nameCmp.setCustomValidity("Name value is required");
        } else {
            nameCmp.setCustomValidity(""); // clear previous value
        }
        nameCmp.reportValidity();

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

        if (!emailCmp.value) {
            emailCmp.setCustomValidity("Email value is required");
        } else {
            emailCmp.setCustomValidity(""); // clear previous value
        }
        emailCmp.reportValidity();
    }
}

Output :

custom-validation-in-lightning-web-component-output-techdicer
custom-validation-in-lightning-web-component-output-techdicer

Reference :

  1. Salesforce

You may also like

Leave a Comment