How to create a custom form validation and display required Error message upon handle input change in Lightning web component – LWC | create a custom form validation in lwc

6,328 views


Hey guys, today in this post we are going to learn about How to create a custom form validation and display required Error message upon handle input change in Lightning web component – LWC.

Files we used in this post example:-

lwcFormValidation.html Lightning Web Component HTML Template HTML file for used to write HTML element for user interface..
lwcFormValidation.js Lightning Web Component JavaScript It is holding Form Validation function that is display the required Error message on handle changing lightning input field.
lwcFormValidation.js-meta.xml XML Meta File It is used for where this lightning web component you want to exposed

Live Demo

create a custom form validation in lwc -- w3web.net

 

You can download file directly from github by Click Here.

 
 

Other related post that would you like to learn in Salesforce

Step 1:- Create Lightning Web Component : lwcFormValidation.html

SFDX:Lightning Web Component >> New >> lwcFormValidation.html

lwcFormValidation.html [Lightning Web Component HTML]

  1.   <template>
  2.     <lightning-card title="Create a custom form validation in Lightning web component - LWC" icon-name="custom:custom12" size="small"> 
  3.         <div class="slds-grid slds-wrap">
  4.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom--medium">
  5.                <lightning-Input type="text" label="First Name" value={firstName} name="firstName" class="firstName" onchange={handleChangeValidation}></lightning-input>
  6.             </div>
  7.  
  8.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom--medium">
  9.                <lightning-Input type="text"  label="Last Name" value={lastName} name="lastName" class="lastName" onchange={handleChangeValidation}></lightning-input>
  10.             </div>
  11.  
  12.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom--medium">
  13.                <lightning-Input type="text" label="Email" value={userEmail} name="userEmail" class="userEmail" onchange={handleChangeValidation}></lightning-input>
  14.             </div>
  15.  
  16.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom--medium">
  17.                <lightning-Input type="phone" label="Phone" value={userPhone} name="userPhone" class="userPhone" onchange={handleChangeValidation}></lightning-input>
  18.             </div>
  19.  
  20.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom--medium">
  21.                <lightning-input type="checkbox" label="Status" name="statusCheckbox" class="statusActive" onchange={handleChangeValidation}></lightning-input>
  22.             </div>
  23.  
  24.  
  25.          </div>
  26.  
  27. <br/><br/>
  28.    <!--Start RelatedTopics Section-->
  29. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  30.  
  31.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  32.  
  33.             <br/><br/>
  34.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
  35.             <div style="display:block; overflow:hidden;"> 
  36.                 <div style="width: 50%; float:left; display:inline-block">
  37.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  38.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  39.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  40.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  41.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  42.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  43.                     </ul>
  44.             </div>
  45.  
  46.             <div style="width: 50%; float:left; display:inline-block">
  47.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  48.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  49.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  50.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  51.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  52.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  53.                     </ul>
  54.                 </div>
  55.                <div style="clear:both;"></div> 
  56.                <br/>
  57.                 <div class="youtubeIcon">
  58.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  59.                 </div>
  60.     </div>
  61.  
  62. </div>
  63.  
  64.   <!--End RelatedTopics Section-->
  65.     </lightning-card>
  66. </template>

Step 2:- Create Lightning Web Component : lwcFormValidation.js

SFDX:Lightning Web Component >> New >> lwcFormValidation.js

lwcFormValidation.js [LWC JavaScript File]

  1.   import { LightningElement } from 'lwc';
  2.  
  3. export default class LwcFormValidation extends LightningElement {
  4.  
  5.     handleChangeValidation(event){
  6.       let getFirstName = event.target.name;
  7.       let getLstName = event.target.name;
  8.       let getUserEmail = event.target.name;
  9.       let getUserPhone = event.target.name;
  10.       let getStatusActive = event.target.name;
  11.       let getCityName = event.target.name;
  12.  
  13.  
  14.       if(getFirstName === "firstName"){
  15.           let firstName = this.template.querySelector('.firstName');
  16.           let firstNameVal = firstName.value;
  17.           if(!firstNameVal){
  18.             firstName.setCustomValidity('Please Enter the First Name');
  19.           }else{
  20.             firstName.setCustomValidity('');
  21.           }
  22.           firstName.reportValidity();
  23.       }
  24.  
  25.  
  26.       else if(getLstName === "lastName"){
  27.         let lastName = this.template.querySelector('.lastName');
  28.         let lastNameVal = lastName.value;
  29.         if(!lastNameVal){
  30.             lastName.setCustomValidity('Please Enter the Larst Name');
  31.         }else{
  32.             lastName.setCustomValidity('');
  33.         }
  34.         lastName.reportValidity();
  35.        }
  36.  
  37.  
  38.        else if(getUserEmail === "userEmail"){
  39.         let userEmail = this.template.querySelector('.userEmail');
  40.         let userEmailVal = userEmail.value;
  41.         if(!userEmailVal){
  42.             userEmail.setCustomValidity('Please Enter the Email Id');
  43.         }else{
  44.             userEmail.setCustomValidity('');
  45.         }
  46.         userEmail.reportValidity();
  47.        }
  48.  
  49.  
  50.        else if(getUserPhone === "userPhone"){
  51.         let userPhone = this.template.querySelector('.userPhone');
  52.         let userPhoneVal = userPhone.value;
  53.         if(!userPhoneVal){
  54.             userPhone.setCustomValidity('Please Enter the Email Id');
  55.         }else{
  56.             userPhone.setCustomValidity('');
  57.         }
  58.         userPhone.reportValidity();
  59.        }
  60.  
  61.  
  62.        else if(getStatusActive === "statusCheckbox"){
  63.         let statusCheckbox = this.template.querySelector('.statusActive');
  64.         let statusCheckboxVal = statusCheckbox.checked;
  65.         if(!statusCheckboxVal){
  66.             statusCheckbox.setCustomValidity('Please Check Mark the Status Checkbox');
  67.         }else{
  68.             statusCheckbox.setCustomValidity('');
  69.         }
  70.         statusCheckbox.reportValidity();
  71.        }        
  72.  
  73.     }
  74.  
  75. }

Step 3:- Create Lightning Web Component : lwcFormValidation.js-meta.xml

SFDX:Lightning Web Component >> New >> lwcFormValidation.js-meta.xml

lwcFormValidation.js-meta.xml [LWC Meta Data XML]

  1.  <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>45.0</apiVersion>
  4.     <isExposed>true</isExposed>
  5.     <targets>
  6.         <target>lightning__AppPage</target>
  7.         <target>lightning__RecordPage</target>
  8.         <target>lightning__HomePage</target>
  9.         <target>lightning__Tab</target>
  10.       </targets>
  11. </LightningComponentBundle>

create a custom form validation in lwc -- w3web.net

Further post that would you like to learn in Salesforce

 


 

FAQ (Frequently Asked Questions)

What are required pieces of a validation rule?

A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of 'True' or 'False'. Validation rules also include an error message to display to the user when the rule returns a value of “True” due to an invalid value.

How do I show alert in LWC?

Lightning Web component(LWC) can send a toast notification that pops up to alert users of success, error or warning. A toast can also simply provide information. To display a toast notification in Lightning Experience or Lightning communities, import ShowToastEvent from the lightning/platformShowToastEvent module.

How do you display error message below input field in lightning component?

All you have to do is check the validity attribute of your lightning:input , and your configured error messages will appear below it automatically.

Related Topics | You May Also Like

Our Free Courses →

👉 Download App to Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Download App to Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration

 
 
🌩️ Download App to Get Free Course Access: -

Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment