0

The issue with above approach is that the form is not getting submitted. As we have not defined any type for lightning-button. Yet, it is displaying error messages correctly but I am stuck on how to manually submit the form in case of no errors.

I tried defining lightning-button type as 'submit' :-

<lightning-button variant="brand" type="submit" name="save" label="Save" onclick={handleClick}></lightning-button>

But in this case it shows the alert but once I click ok, it saves that record. Ideally it should go back to that page to fix those issues.

I also tried Custom Validity Error Messages as per the documentation. But got stuck into the same issue where if not using type="Submit" in lightning-button - It never submit that form and if using lightning-button type="Submit" it submit the form no matter what.

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {

    register(event) {
        var inputCmp = this.template.querySelector(".inputCmp");
        var value = inputCmp.value;
        // is input valid text?
        if (value === "John Doe") {
            inputCmp.setCustomValidity("John Doe is already registered");
        } else {
            inputCmp.setCustomValidity(""); // if there was a custom error before, reset it
        }
        inputCmp.reportValidity(); // Tells lightning-input to show the error right away without needing interaction
    }
}
0

You can remove the type on button and submit the form in javascript code as below:

handleClick(event) {
    event.preventDefault();
    this.validForm = true;
    // check for validations and set validForm
    if (this.validForm) {
        this.template.querySelector('lightning-record-edit-form').submit();
    } else {
        this.showToast();
    }
}
  • you set this.validForm = true; and then you check if it's true on the very next line? – Movsar Bekaev Jan 16 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.