How to Add Custom Validation in Salesforce Lightning Web Components? : Abhijeet
by: Abhijeet
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of Custom Validation in Salesforce Lightning Web Components (LWC) In Salesforce Lightning Web Components (LWC), you can enhance user input validation for forms beyond the default HTML5 validations. This tutorial provides a step-by-step guide on how to implement custom validation for input fields, ensuring that user inputs meet specific criteria before they are processed or saved. #### Key Details: 1. **Custom Validation Methods**: The tutorial focuses on using `reportValidity()` and `setCustomValidity()` methods to create custom validation rules. 2. **Single Field Validation**: An example is provided for validating a number input (1-100). If the input is invalid, an error message is displayed. 3. **Multiple Field Validation**: Another example demonstrates how to validate both email and phone number fields, ensuring the email contains '@' and '.com', and the phone number is a valid 10-digit number. 4. **Implementation Steps**: - Create an LWC component and add the necessary HTML and JavaScript code. - Use `setCustomValidity()` to set error messages and `reportValidity()` to display them. - Deploy the component to Lightning pages for testing. #### Additional Context: Custom validation is particularly useful in scenarios where standard validation rules are insufficient. By implementing these methods, developers can ensure data integrity and improve user experience in Salesforce applications. ### Conclusion This tutorial illustrates how to add custom validation in Salesforce LWC, enhancing the capability to handle user inputs effectively. By following the provided examples, developers can implement robust validation logic tailored to their specific requirements. ### Relevant Hashtags for SEO #Salesforce #LightningWebComponents #LWC #CustomValidation #WebDevelopment #SalesforceDevelopment #UserInputValidation #SalesforceTutorial #JavaScript #FrontendDevelopment
In Salesforce Lightning Web Components, we can add validation to the input fields of the component, such as when the input comes from a user through a form created through LWC components. By using validation, we can ensure that user inputs meet specific criteria before processing or saving a record through LWC components.
In this Salesforce LWC tutorial, we will learn how to add custom validation in Salesforce Lightning Web Components using validation methods such as reportValidity() and setCustomValidity().
Custom Validation in Salesforce Lightning Web Components (LWC)
In Salesforce Lightning Web Components (LWC), we can add validation rules on input fields apart from the standard HTML5 or Salesforce-provided validation with custom validation. This is useful when we need to implement complex validation logic that is not achievable with standard attributes like required, pattern, or minlength.
Implement Validation in LWC components with Custom Validation
In this example, I will explain how we can add validation to the input fields of a custom LWC form. Now, open the VS code or Salesforce developer console and follow the steps below.
1. First, create an LWC component and enter the component name in the camel case; then, for the validation of the number field, enter the code below in the HTML template.
The code below is going to validate the number input from the user, which should be between 1-100.
<template>
<lightning-card title="Custom Validation Example">
<div class="slds-m-around_medium">
<lightning-input type="text" label="Enter Number (1-100)"
data-id="numberInput"
onchange={handleInputChange}>
</lightning-input>
<div class="error-message slds-text-color_error" if:true={errorMessage}>
{errorMessage}
</div>
<lightning-button label="Validate" onclick={validateInput}></lightning-button>
</div>
</lightning-card>
</template>
2. After this, enter the code below in the LWC component’s JS file.
import { LightningElement, track } from 'lwc';
export default class CustomValidation extends LightningElement {
@track errorMessage = '';
handleInputChange(event) {
this.errorMessage = '';
}
validateInput() {
const inputElement = this.template.querySelector('[data-id="numberInput"]');
const value = inputElement.value;
if (!value || isNaN(value) || value < 1 || value > 100){
this.errorMessage = 'Please enter a number between 1 and 100.';
inputElement.setCustomValidity('Invalid input.');
} else {
this.errorMessage = '';
inputElement.setCustomValidity(''); }
inputElement.reportValidity();
}
}
In the above code, the validateInput() method will check whether the entered number is within the valid range. If the input is invalid, then setCustomValidity() will set an error message, and the reportValidity() method will display that error message through the browser.
The handleInputChange will ensure the error message disappears when the user re-enters the value in the input field.
3. Make the component exposed to the Lightning page using the code below inside the LightningComponentBundle tag.
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
4. After this, deploy the component to the Lightning page layout and test it by entering invalid input ( value more than 100).

An error message will appear on the screen as we enter the value exceeding the validation limit.
This way, we can validate the input fields in Salesforce Lightning Web Components using the validateInput() and reportValidity() methods.
Implement Validation on multiple LWC components
Let’s take an example for multiple LWC field validation where we will implement validation on the email and phone fields.
1. Enter the code below in the HTML file of the LWC component that includes the email and phone fields and also the button that will call the logic from the Js file for validation.
<template>
<lightning-card title="Multi-Field Validation">
<div class="slds-m-around_medium">
<lightning-input type="email" label="Enter Email" data-id="emailInput"></lightning-input>
<lightning-input type="tel" label="Enter Phone Number" data-id="phoneInput"></lightning-input>
<lightning-button label="Validate All" onclick={validateAll}></lightning-button>
</div>
</lightning-card>
</template>
2. Now, enter the code below in the Js file of the component to handle the validation logic.
import { LightningElement } from 'lwc';
export default class MultiFieldValidation extends LightningElement {
validateAll() {
const emailInput = this.template.querySelector('[data-id="emailInput"]');
const phoneInput = this.template.querySelector('[data-id="phoneInput"]');
let isValid = true;
if(!emailInput.value.includes('@') || !emailInput.value.includes('.com')){
emailInput.setCustomValidity('Enter a valid email address.');
isValid = false;
} else {
emailInput.setCustomValidity('');
}
const phonePattern = /^[0-9]{<11,}$/;
if (!phonePattern.test(phoneInput.value)){
phoneInput.setCustomValidity('Enter a valid 10-digit phone number.');
isValid = false;
} else {
phoneInput.setCustomValidity('');
}
emailInput.reportValidity();
phoneInput.reportValidity();
if (isValid) {
alert('All inputs are valid!');
}
}
}
In the above code, the validateAll() method will be called when the user validates both input fields. To validate the input of email that it should include ‘@‘ and ‘com,’ we have defined the condition.
(!emailInput.value.includes('@') || !emailInput.value.includes('.com'))
For the validation of the phone field that it should be exactly a 10-digit number, we have defined the condition.
const phonePattern = /^[0-9]{<11,}$/;
4. At last, expose the component to the Lightning pages and deploy it on the Lightning App page.
5. In the input fields, when entering the invalid input and clicking Validate, we got the error message for the invalid values.

This way, we can define and implement the validation logic for the multiple fields in the Salesforce LWC components.
Conclusion
In this Salesforce tutorial, we have learned to add custom validation in Salesforce Lightning Web Components. This is useful when the standard validations are not enough to validate the fields.
In the above steps, we have used methods such as validateInput() and reportValidity() to create a custom validation for LWC input fields, and we also learned to add custom validation on multiple fields in an LWC component.
You may also like to read:
- How to Call Apex Methods From LWC in Salesforce?
- How to Create and Deploy LWC Component in Salesforce?
The post How to Add Custom Validation in Salesforce Lightning Web Components? appeared first on SalesForce FAQs.
February 10, 2025 at 09:28AM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Abhijeet
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment