2

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?
  }
}
<template>
    <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}>

</template>
6

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

Yes.

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) => {
                    inputCmp.reportValidity();
                    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.');
    }
}

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.