Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How can I use reportvalidity lwc to stop execution?

Asked by Aashish Chaursiya Aug 29, 2023 4.9K views 3 answers
Share

About this question

 I have an LWC form that comprises a lightning-record-edit-form and lightning-input fields, and as I have to do some custom logic, I have to override the submit button with Apex. I am trying to fire specific validation rules defined against the lightning-input field by applying reportValidity(), which I can do. However, as the rule fires, I want to stop the execution, which is not happening, and the code is still reaching the Apex. How can the execution be stopped by using reportvalidity lwc if reportValidity() makes errors on the lightning-input field?

The HTML code:


    
     
     

JS as follows:
validateFields(event) {
    this.template.querySelectorAll('lightning-input-field').forEach(element => {
                element.reportValidity();
            });
    //check if there is an error. not sure how to check if reportValidity throws an error as the code proceeds to execute apex even when there is an error
        
     let isError = this.template.querySelector(".slds-has-error");
    
    //if no error then only call apex from handleSubmit
     if(!isError) {
            this.template.querySelector("lightning-record-edit-form").submit();
        }
    }

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Feb 5, 2025

In Lightning Web Components (LWC), reportValidity() is used to check if a form field is valid and display an error message if it's not. However, it does not automatically stop execution like return false in traditional JavaScript. You need to manually prevent further execution based on its result.

How to Use reportValidity() to Stop Execution?

1. Call reportValidity() on Input Fields

  • It highlights invalid fields with an error message.
  • Returns true if the field is valid, otherwise false.

2. Use Conditional Logic to Stop Execution

  • If a field is invalid, return early to prevent further code execution.

Example Code

Here’s how to validate multiple fields and stop execution if any are invalid:

handleFormSubmit() {
    const inputFields = this.template.querySelectorAll('lightning-input');
    let isValid = true;
    inputFields.forEach(field => {
        if (!field.reportValidity()) {
            isValid = false;  // Stop execution if a field is invalid
        }
    });
    if (!isValid) {
        return;  // Prevent further execution
    }
    // Proceed with form submission or further logic
    console.log('Form submitted successfully!');
}

How This Works?

✅ Loops through all lightning-input fields.

✅ Calls reportValidity() on each field.

✅ If any field is invalid, sets isValid = false.

✅ Uses if (!isValid) return; to stop execution.


Was this helpful?

Ranjana Admin JanBask Expert

Answered on May 7, 2024

In Lightning Web Components (LWC), the reportValidity() method is used to trigger native browser form validation on a specific input element or a form containing that element. It doesn't stop the execution of code directly. However, you can use it in combination with other techniques to achieve the desired behavior of stopping execution based on form validation.

Here's a general approach:

Usage of reportValidity(): Call the reportValidity() method on the input element or form you want to validate. This will trigger the browser's built-in form validation.

Check Validation Result: After calling reportValidity(), check the validation result. You can do this by accessing the validity property of the input element or form.

Stop Execution Based on Validation Result: Depending on the validation result, you can choose to stop the execution of further code. For example, if the form is not valid, you can return early from a function or prevent a form submission.

Here's an example:

/ Assuming you have a form with an input element
// and a submit button in your LWC HTML template




// JavaScript file for the LWC component
import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
    handleSubmit(event) {
        event.preventDefault(); // Prevent default form submission behavior
        // Validate the form using reportValidity()
        const isValid = this.template.querySelector('form').reportValidity();
        // Check if the form is valid
        if (!isValid) {
            // Stop execution if the form is not valid
            return;
        }
        // Continue with form submission or further processing
    }
}

In this example:

The handleSubmit() method is triggered when the form is submitted.

We prevent the default form submission behavior using event.preventDefault() to handle form submission programmatically.

We then call reportValidity() on the form element to trigger browser form validation.

The result of reportValidity() is stored in the isValid variable.

If the form is not valid (isValid is false), we return early from the function, effectively stopping further execution.

This way, you can use reportValidity() to stop the execution of further code based on form validation results in your LWC.


Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.