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

Happy Sharing...

Everyone has their own favorites, so please feel free to share yours in the comments below!

Comments

  1. What does the ... mean in [...this.template.querySelectorAll('.validValue')]

    ReplyDelete
    Replies
    1. That is query Selector same like document.getElementsByClass(). LWC use querySelectorAll function.

      Delete
  2. Hi Sanjay
    I 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"

    ReplyDelete
    Replies
    1. Please share your code with me on "sanjayibirds2013@gmail.com" so i can help you.

      Delete
    2. Hi @snajay,

      I am getting the same error, have you suggested any solution for this.

      Delete
  3. Hi Sanjay,

    I'm getting the same error as GK. How can i use setCustomValidity with a queried element with template.querySelector?
    Thanks!

    ReplyDelete
    Replies
    1. All input box should have validValue class name.

      Delete
  4. when I use inputCmp.checkValidity() i get error inputCmp.checkValidity is not a function , and when i use inputCmp.checkValidity , it throws undefined

    ReplyDelete

Post a Comment

Popular posts from this blog

Salesforce LWC : Compact Layout on Hover

Salesforce LWC With Third Party JS : D3

Communications between Lightning Components : Salesforce