How can I use reportvalidity lwc to stop execution?

2.1K    Asked by Aashishchaursiya in Salesforce , Asked on Aug 29, 2023

 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();
        }
    }

Validation rules cannot be called separately from DML operations: Fire Validation Rule from Apex. Kindly note theTrigger Order of Execution:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm If you are trying to use lightning-record-edit-form as a form to collect the correct input without saving it to the DB and then handle it through another Apex class, then it cannot be done. You should create a custom lookup component, using input fields, and handling all the logic client side, then pass the input to your class, or else lightning-record-edit-form must be saved to the database to run “reportValidity” and to return Validation Rule errors. Please look at the section “Overriding Default Behaviors” https://developer.salesforce.com/docs/component-library/bundle/lightning-record-edit-form/documentation ustom error messages cannot be set on the input field like in the case of input setCustomValidity(). But the errors can be handled in a separate component / UI feature – here, errors had been added by me in an array.

customErrors = [];
handleSubmit(event) {
    event.preventDefault();
    this.customErrors = [];
    let isValid = [...this.template.querySelectorAll('lightning-input-field')].reduce( (val, inp) => {
        let inpVal = true;
        // Custom Logic
        switch (inp.fieldName) {
            case 'Name':
                inpVal = inp.value == 'Logic' ? true : false;
                if (!inpVal) { this.customErrors.push('Custom Error'); }
                break;
            default:
                inpVal = true;
                break;
        }
        return val && inpVal;
    }, true);
    if (isValid) {
        this.template.querySelector('lightning-record-edit-form').submit();
        // Validation Rules will run and return errors after the submit / DML operation
    }
}
The result of all the reportValidity() needs to be recorded, which can be done quickly with the help of the reduce function mentioned above. Depending on the result, you can either throw an error message or submit the save.
handleSave() {
    // If all fields aren't validated, throw error message
    if (!this.validateFields()) {
        const toast = new ShowToastEvent({
            message: "Review all error messages below to correct your data.",
            variant: "error",
        });
        this.dispatchEvent(toast);
    }
    // Otherwise submit save
    else {
        this.template.querySelector("lightning-record-edit-form").submit();
    }
}
validateFields() {
    return [...this.template.querySelectorAll("lightning-input-field")].reduce((validSoFar, field) => {
        // Return whether all fields up to this point are valid and whether current field is valid
        // reportValidity returns validity and also displays/clear message on element based on validity
        return (validSoFar && field.reportValidity());
    }, true);
}

Your Answer

Answers (2)

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.


1 Week

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.


9 Months

Interviews

Parent Categories