How can I use reportvalidity lwc to stop execution?

501    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

Interviews

Parent Categories