I created a LWC with two lightning-input tags marked as required and a lightning-button tag. I am struggling to display required error message on submitting the button. I get error message when I don't enter any text and blur out of the input field. But when I submit I don't see the error messages. Do I need to write my own logic to display custom message?

Is there a way to get the value of the input from a class defined on the lightning-input instead of getting from the bind property?

import { LightningElement, track } from 'lwc';

export default class Avisvintracker1 extends LightningElement {
  @track test;
  @track test2;

  submit() {
      // How Can I trigger error if the user doesn't fill the form?
    <lightning-input label="test" value={test} required></lightning-input>
    <lightning-input label="test2" value={test2} required></lightning-input>
    <lightning-button variant="brand" label="Brand action" title="Brand action" class="slds-m-left_x-small" onclick={submit}>


1 Answer 1


Do I need to write my own logic to display custom message?


This is from documentation for lightning-input:

For example, you have the following form with several fields and a button. To display error messages on invalid fields, use the reportValidity() method.

Your submit function should implement something as mentioned in the documentation (as below). I did a quick test and once the input fields are validated, you are able to view the required field error on the fields.

@track value = "initial value";

handleClick(evt) {
    console.log('Current value of the input: ' + evt.target.value);

    const allValid = [...this.template.querySelectorAll('lightning-input')]
        .reduce((validSoFar, inputCmp) => {
                    return validSoFar && inputCmp.checkValidity();
        }, true);
    if (allValid) {
        alert('All form entries look valid. Ready to submit!');
    } else {
        alert('Please update the invalid form entries and try again.');
  • Hi Jayant, Can you please tell me what the significance of '...this.template' is vs 'this.template'. I was not able to get much details on this. Commented Aug 26, 2020 at 10:50
  • 1
    @ApexSrinivas the "3 dots" before "this" is called as spread operator. This would take iterable such as array or string and expand it in to individual elements. In this case, as the querySelectorAll would return a NodeList, the spread operator would pass each individual element from the list to the reduce function. More info on the spread operator here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… codeburst.io/what-are-three-dots-in-javascript-6f09476b03e1
    – Karthik
    Commented Jul 7, 2021 at 18:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .