Lightning Validation with Custom Message : Aura vs LWC
Lightning Validation : Aura Component
LightningValidation.cmp (Component)
<aura:component>
<aura:attribute name="firstName" type="String" default="" />
<aura:attribute name="lastName" type="String" default="" />
<div class="row">
<h2 class="header">Fill Information</h2>
<lightning:input aura:id="validfield" onblur="{!c.handleCustomValidation}" name="firstName"
minlength="3" fieldLevelHelp="This First Name show in Website"
messageWhenTooShort="Your entry must be at least 3 characters."
required="true" value="{!v.firstName}" placeholder="First name"
label="Please enter your First Name" valueMissing="Please enter your First Name"/>
<lightning:input aura:id="validfield" onblur="{!c.handleCustomValidation}" name="lastName"
minlength="3" fieldLevelHelp="This Last Name show in Website"
messageWhenTooShort="Your entry must be at least 3 characters."
required="true" value="{!v.lastName}" placeholder="Last name"
label="Please enter your Last Name" valueMissing="Please enter your Last Name"./>
</div>
<div class="row">
<lightning:button type="submit" label="Submit" onclick="{!c.handleValidation}" />
</div>
</aura:component>
LightningValidation.js (JS Controller )
({
handleValidation : function(cmp) {
var allValid = cmp.find('validfield').reduce(function (validSoFar, inputCmp) {
inputCmp.reportValidity();
return validSoFar && inputCmp.checkValidity();
}, true);
if (allValid) {
//Submit information on Server
} else {
alert('Please fill required and update all invalid form entries');
}
},
handleCustomValidation : function(cmp,event) {
var inputValue = event.getSource().get("v.value");
// is input valid text?
if (inputValue.indexOf('@')>=0) {
inputCmp.setCustomValidity("Please Don't include '@' in name");
} else {
inputCmp.setCustomValidity(""); // reset custom error message
}
inputCmp.reportValidity();
}
})
Lightning Validation : Lightning Web Component
LightningValidation.html (Template)
<template>
<lightning-input label="First name" class="validValue inputFirstName" onblur="{!handleCustomValidation}"
minlength="3" field-level-help="This First Name show in Website"
message-when-bad-input="Your entry must be at least 3 characters."
placeholder="First name" message-when-value-missing="Please enter your First Name"
required>
</lightning-input>
<lightning-input label="Last name" class="validValue inputLastName" onblur="{!handleCustomValidationLastName}"
minlength="3" field-level-help="This First Name show in Website"
message-when-bad-input="Your entry must be at least 3 characters."
placeholder="Last name" message-when-value-missing="Please enter your Last Name"
required>
</lightning-input>
<lightning-button type="submit"
label="Submit"
onclick={handleValidation}>
</lightning-button>
</template>
LightningValidation.Js (JS Controller )
import { LightningElement, track } from 'lwc';
export default class LightningValidation extends LightningElement {
handleValidation() {
const allValid = [...this.template.querySelectorAll('.validValue')]
.reduce((validSoFar, inputCmp) => {
inputCmp.reportValidity();
return validSoFar && inputCmp.checkValidity();
}, true);
if (allValid) {
//Submit information on Server
} else {
alert('Please fill required and update all invalid form entries');
}
}
handleCustomValidationFirstName(event) {
let inputValue = event.target.value;
let inputFirstName=this.template.querySelector(".inputFirstName");
if(inputValue.indexOf('@')>=0) {
//set an error
inputFirstName.setCustomValidity("Please Don't include '@' in First name");
inputFirstName.reportValidity();
}else {
//reset an error
inputFirstName.setCustomValidity('');
inputFirstName.reportValidity();
}
}
handleCustomValidationLastName(event) {
let inputValue = event.target.value;
let inputLastName=this.template.querySelector(".inputLastName");
if(inputValue.indexOf('@')>=0) {
//set an error
inputLastName.setCustomValidity("Please Don't include '@' in Last name");
inputLastName.reportValidity();
}else {
//reset an error
inputLastName.setCustomValidity('');
inputLastName.reportValidity();
}
}
}
LightningValidation.js-meta.xml (XML for Config File in Salesforce)
<lightningcomponentbundle fqn="LightningValidation" xmlns="http://soap.sforce.com/2006/04/metadata">
<apiversion>45.0</apiversion>
<isexposed>true</isexposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</lightningcomponentbundle>
Note: After save whole code you will drag and drop code into Lightning Record Detail Page of Any Object
What does the ... mean in [...this.template.querySelectorAll('.validValue')]
ReplyDeleteThat is query Selector same like document.getElementsByClass(). LWC use querySelectorAll function.
DeleteHi Sanjay
ReplyDeleteI am getting error reportValidity() is not a function while using this.template.querySelectorAll('.className')
I have different input types in my form (Like lightning-input, lightning-input-rich-text). I have given them the class = "validValue"
I got same error
DeletePlease share your code with me on "sanjayibirds2013@gmail.com" so i can help you.
DeleteHi @snajay,
DeleteI am getting the same error, have you suggested any solution for this.
Hi Sanjay,
ReplyDeleteI'm getting the same error as GK. How can i use setCustomValidity with a queried element with template.querySelector?
Thanks!
All input box should have validValue class name.
Deletewhen I use inputCmp.checkValidity() i get error inputCmp.checkValidity is not a function , and when i use inputCmp.checkValidity , it throws undefined
ReplyDeleteThank you for sharing wonderful information
ReplyDeletesalesforce cpq online training Hyderabad
salesforce cpq online training India