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
}
}
Best Answer
You can remove the
type
on button and submit the form in javascript code as below: