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 :
- Create a simple form.
- Validate each field with a custom error message.
- Show user-like error messages.
- 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 :
Reference :
What’s your Reaction?
+1
6
+1
+1
+1
+1
2
+1
1