How to Add Custom Validation in Salesforce Lightning Web Components?

In Salesforce Lightning Web Components, we can add validation to the input fields of the component, such as when a user provides the input through a form created using 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 to input fields, in addition to 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, such as 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 VS Code or the Salesforce Developer Console and follow the steps below.

1. First, create an LWC component and enter the component name in camel case; then, for the validation of the number field, enter the code below in the HTML template.

The code below will validate the number input from the user, which should be between 1 and 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 checks whether the entered number falls 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.

<i