Custom Validation in a Lightning Input Field on Click Button in Lightning Component Salesforce | required field validation to display error messages in Salesforce lightning component

4,084 views


Hey guys, today in this post we are going to learn about How to create a form and validate all fields on a single click of button in lightning component.

Why are validation rules used?

We use form validation whenever we need to input information that is expected to some requirement from user.

There are two type of validation rule standards:- Server Side Validation and Client Side Validation.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
   

Server Side Validation:- It is performed by server side. When we click on a button the button functionality call a method that is connected through server and it’s get all information from server.

Client Side Validation:- Client side validation performed by JavaScript function. Where does not need to connect to server. It is working very fast because it helps to reduce the server side lode.

In this example I am creating a client side validation. So go through the below points step by step.

Live Demo

Form Validation - w3web.net

 

You can download file directly from github by Click Here.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

 

 

Other related post that would you like to learn in Salesforce

 

Step:-1

formValidationCmp.cmp [Lightning Component]

  1.       <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >   
  2.  
  3.  
  4.     <div class="slds">
  5.         <div class="slds-grid slds-wrap">
  6.             <div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  7.                 <div class="slds-form-element">
  8.                     <label class="slds-form-element__label">Name</label>
  9.                     <div class="slds-form-element__controller">
  10.                         <ui:inputText class="slds-input" value="" aura:id="userName"/>
  11.                     </div>
  12.                 </div>
  13.             </div>
  14.  
  15.         </div>
  16.  
  17.         <div class="slds-grid slds-wrap">
  18.             <div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  19.                 <div class="slds-form-element">
  20.                     <label class="slds-form-element__label">Email</label>
  21.                     <div class="slds-form-element__controller">
  22.                         <ui:inputEmail class="slds-input" value="" aura:id="userEmail"/>
  23.                     </div>
  24.                 </div>
  25.             </div>
  26.  
  27.         </div>
  28.  
  29.         <div class="slds-grid slds-wrap">
  30.             <div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  31.                 <div class="slds-form-element">
  32.                     <label class="slds-form-element__label">Phone</label>
  33.                     <div class="slds-form-element__controller">
  34.                         <ui:inputPhone class="slds-input" value="" aura:id="userPhone"/>
  35.                     </div>
  36.                 </div>
  37.             </div>
  38.  
  39.         </div>
  40.  
  41.         <div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  42.             <div class="slds-form-element">
  43.                 <label class="slds-form-element__label">State</label>
  44.                 <div class="slds-form-element__controller">
  45.                     <ui:inputSelect class="slds-select" aura:id="userState" value="">
  46.                         <ui:inputSelectOption text="--None--"/>
  47.                         <ui:inputSelectOption text="Delhi"/>
  48.                         <ui:inputSelectOption text="Haryana"/>
  49.                         <ui:inputSelectOption text="Karnataka"/>
  50.                     </ui:inputSelect>
  51.                 </div>
  52.             </div>
  53.         </div>
  54.  
  55.         <div class="slds-form--inline slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  56.             <div class="slds-form-element" aura:id="redCheck">
  57.                 <div class="slds-form-element__control">
  58.                     <div class="slds-checkbox">                      
  59.                         <input type="checkbox" name="options" aura:id="checkbox1" id="checkbox1" value="" />
  60.                         <label class="slds-checkbox__label" for="checkbox1">
  61.                             <span class="slds-checkbox_faux"></span>
  62.                             <span class="slds-form-element__label">Red</span>
  63.                         </label>
  64.                     </div>
  65.                 </div>                  
  66.             </div>
  67.  
  68.             <div class="slds-form-element" aura:id="greenCheck">
  69.                 <div class="slds-form-element__control">
  70.                     <div class="slds-checkbox">                      
  71.                         <input type="checkbox" name="options" aura:id="checkbox2" id="checkbox2" value=""  />
  72.                         <label class="slds-checkbox__label" for="checkbox2">
  73.                             <span class="slds-checkbox_faux"></span>
  74.                             <span class="slds-form-element__label">Green</span>
  75.                         </label>
  76.                     </div>
  77.                 </div>                  
  78.             </div>
  79.  
  80.         </div>
  81.  
  82.  
  83.         <div class="slds-form--inline slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  84.             <div class="slds-form-element">
  85.                 <div class="slds-form-element__control">
  86.                     <span class="slds-radio">
  87.                       <input type="radio" id="radio1" value="" name="default" checked="" />
  88.                       <label class="slds-radio__label" for="radio1">
  89.                         <span class="slds-radio_faux"></span>
  90.                         <span class="slds-form-element__label">Radio Label One</span>
  91.                       </label>
  92.                     </span>                    
  93.                   </div>
  94.             </div>
  95.  
  96.             <div class="slds-form-element">
  97.                 <div class="slds-form-element__control">
  98.                     <span class="slds-radio">
  99.                       <input type="radio" id="radio2" value="radio-43" name="default" checked="" />
  100.                       <label class="slds-radio__label" for="radio2">
  101.                         <span class="slds-radio_faux"></span>
  102.                         <span class="slds-form-element__label">Radio Label Two</span>
  103.                       </label>
  104.                     </span>                    
  105.                   </div>
  106.             </div>
  107.  
  108.         </div>
  109.  
  110.        <div class="slds-form--inline slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium"> 
  111.         <div class="slds-text-align--center slds-m-top--medium">
  112.             <button class="slds-button slds-button--brand" onclick="{!c.submitScoreAction}">Submit</button>
  113.         </div>
  114.         </div> 
  115.         <br/>
  116.  
  117.  
  118. <br/><br/>
  119.    <!--Start RelatedTopics Section-->
  120. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  121.  
  122.             <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>
  123.  
  124.             <br/><br/>
  125.             <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>
  126.             <div style="display:block; overflow:hidden;"> 
  127.                 <div style="width: 50%; float:left; display:inline-block">
  128.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  129.                         <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>
  130.                         <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>
  131.                         <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>
  132.                         <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>
  133.                         <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>
  134.                     </ul>
  135.             </div>
  136.  
  137.             <div style="width: 50%; float:left; display:inline-block">
  138.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  139.                         <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>
  140.                         <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>
  141.                         <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>
  142.                         <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>
  143.                         <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>
  144.                     </ul>
  145.                 </div>
  146.                <div style="clear:both;"></div> 
  147.                <br/>
  148.                 <div class="youtubeIcon">
  149.                     <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>
  150.                 </div>
  151.     </div>
  152.  
  153. </div>
  154.  
  155.   <!--End RelatedTopics Section-->
  156.  
  157.  
  158.     </div>
  159.  
  160. </aura:component>

 

Step:-2

formValidationCmpController.js [JavaScript File]

  1.       ({
  2. 	submitScoreAction : function(component, event, helper) {
  3.         var isValidate = true;
  4.  
  5.         var userName = component.find('userName');
  6.         var userEmail = component.find('userEmail');
  7.         var userPhone = component.find('userPhone');
  8.         var userState = component.find('userState');
  9.  
  10.  
  11.         var userNameVal = component.find('userName').get('v.value');        
  12.         var userEmailVal = component.find('userEmail').get('v.value');
  13.         var userPhoneVal = component.find('userPhone').get('v.value');
  14.         var userStateVal = component.find('userState').get('v.value');
  15.  
  16.  
  17.         if($A.util.isUndefinedOrNull(userNameVal) || $A.util.isUndefined(userNameVal) || $A.util.isEmpty(userNameVal)){
  18.             userName.set("v.errors",[{message:'Name is required'}]);
  19.             isValidate = false;
  20.         }else{
  21.             userName.set("v.errors",null);
  22.         }        
  23.  
  24.  
  25.         if($A.util.isUndefinedOrNull(userEmailVal) || $A.util.isUndefined(userEmailVal) || $A.util.isEmpty(userEmailVal)){
  26.             userEmail.set("v.errors",[{message:'Email is required'}]);
  27.             isValidate = false;
  28.         }else{
  29.             userEmail.set("v.errors",null);
  30.         }
  31.  
  32.  
  33.         if($A.util.isUndefinedOrNull(userPhoneVal) || $A.util.isUndefined(userPhoneVal) || $A.util.isEmpty(userPhoneVal)){
  34.             userPhone.set("v.errors",[{message:'Phone is required'}]);
  35.             isValidate = false;
  36.         }else{
  37.             userPhone.set("v.errors",null);
  38.         }
  39.  
  40.         if(userStateVal == '--None--'){
  41.             userState.set("v.errors",[{message:'Please select state option'}]);
  42.             isValidate = false;
  43.         }else{
  44.             userState.set("v.errors",null);
  45.         }
  46.  
  47.         if(isValidate){
  48.             //alert('Form submitted successfully');
  49.  
  50.             var toastEvent = $A.get("e.force:showToast");
  51.                 toastEvent.setParams({
  52.                     "title":"Success",
  53.                     "type":"success",
  54.                     "message":"Form submitted successfully.",                        
  55.                 });
  56.                 toastEvent.fire();
  57.  
  58.             $A.get('e.force:refreshView').fire();
  59.         }
  60.  
  61.  
  62. 	},
  63.  
  64.  
  65. })

 

Step:-3

formValidationCmp.css [Style CSS File]

  1.    .THIS {
  2.      background-color:#fff !important;
  3.     border-radius:5px;
  4. }
  5. .THIS .slds-input.has-error, .THIS .slds-select.has-error {
  6.     background-color: rgb(255, 255, 255);
  7.     border-color: rgb(194, 57, 52);
  8.     box-shadow: rgb(194, 57, 52) 0 0 0 1px inset;
  9.     background-clip: padding-box;
  10. }

 

 
 

Further post that would you like to learn in Salesforce

 
 

 

 

 

FAQ (Frequently Asked Questions)

How do you display validation error in lightning component?

To programmatically set and display an error message on a field, use the setCustomValidity() and reportValidity() methods available on the base components. For more information, see the lightning:input documentation.

How do you make fields required in aura?

To make an input field required on the client only, set required attribute to true in lightning:inputField . Use this attribute if you want to require a value in a field before the form can be submitted, and the field isn't marked required in Setup.

How do you display toast message in LWC?

A toast can also simply provide information. To display a toast notification in Lightning Experience or Experience Builder sites, import ShowToastEvent from the lightning/platformShowToastEvent module. The lwc-recipes repo has a component that lets you customize and send a toast so that you can try out the variations.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses β†’

πŸ‘‰ Get Free Course β†’

πŸ“Œ Salesforce Administrators

πŸ“Œ Salesforce Lightning Flow Builder

πŸ“Œ Salesforce Record Trigger Flow Builder

πŸ‘‰ Get Free Course β†’

πŸ“Œ Aura Lightning Framework

πŸ“Œ Lightning Web Component (LWC)

πŸ“Œ Rest APIs Integration



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