How to display the error messages in Lightning webcomponents





registrationForm.html
=====================
<template>
    <lightning-input label="FirstName"></lightning-input>
    <lightning-input label="LastName"></lightning-input>
    <lightning-button label="Submit"  variant="brand" onclick={handleValidate}></lightning-button>
</template>

registrationForm.js
===================
import { LightningElement,track } from 'lwc';
export default class RegistrationForm extends LightningElement {
    @track errors={
        "FirstName":"Please Enter the FirstName",
        "LastName":"Please Enter the LastName"
    };
    handleValidate(){
        this.template.querySelectorAll("lightning-input").forEach(item => {
            let val=item.value;
            let label=item.label;
            if(!val){
                item.setCustomValidity(this.errors[label]);

            }else{
                item.setCustomValidity("");
            }
            item.reportValidity();
        });
    }
}

Comments