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

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

handleClick(event) {
    this.validForm = true;
    // check for validations and set validForm
    if (this.validForm) {
    } else {
  • 2
    you set this.validForm = true; and then you check if it's true on the very next line? – Movsar Bekaev Jan 16 '20 at 12:53
  • Your code example need to be more in-depth as you are setting this.validForm to true and not going through on how to check a form is valid. If you can adjust your code example that will make others be able to understand what you are trying to do. – Gunner1714 Mar 24 '20 at 14:16

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.