Validate lightning-input Tag using the checkValidity() and reportValidity() methods in LWC

checkValidity():

In Lightning Web Components (LWC), the lightning-input component provides the checkValidity() method, which you can use to check the validity of the input field. This method returns a boolean value indicating whether the input satisfies its validation constraints.

reportValidity():

In Lightning Web Components (LWC), the lightning-input component provides the reportValidity() method, which you can use to check the validity of the input field and display error messages if needed. This method is particularly useful when you want to show error messages associated with the input field to the user.

Please find the below example on how to use these 2 methods to Validate and Display error messages in LWC

Create a sample LWC component with 3 lightning-input tags.

HTML


javascript


Explanation:

Step 1: use this.template.querySelectorAll('lightning-input'); to select all the required

<lightning-Input> you want to validate, this will identify all <lightning-Input> which can be assigned to a const array.

Step 2: If you only want specific tags to be added, perform array.slice(0,2) to only have the <lightning-Input> tags that you want to validate.

Step 3: Iterate the array till the array.length and perform array[i].checkValidity() , this returns a Boolean value, true if valid.

Step 4: To add error messages beside the <lightning-Input> tags, you can simply add array[i].reportValidity() if array[i].checkValidity() returns false.


This is how it looks in the UI if we directly click on the Button with Wrong/Empty Input Data.


happy coding!




Comments

Popular posts from this blog

What are Duplicate Rules and Matching Rules? How to Invoke Duplicate and Matching Rules in Salesforce without performing DML operations?

Apex Best Practices

LWC Best Practices