html code

Implementing Custom Validation within a Lightning Web Component

The Lightning component is relatively new, and I faced challenges when trying to implement custom validation for fields, particularly for the ‘lightning-input’ component. There is limited information available on the internet at the moment, and I believe others may be encountering similar difficulties. Fortunately, I was able to find a solution that worked for me, and I would like to share the JavaScript method that enables custom error validation for any field.

In this method, I retrieve the date value and check if it is empty. If it is, I display an error message on the field and return a null value. Otherwise, if there is no error, I remove any existing error message and return the entered value.

/* Method to get input field value */
getinputval() {
    let returnvalue; //assigning temp variable
    var inputCmp = this.template.querySelector(".inputfield"); //getting element
    var value = inputCmp.value; //assigning value to variable
    // is input valid text?
    if (value === "") {
        //adding custom validation
        inputCmp.setCustomValidity("Field is Required!");
        returnvalue = false;
    } else {
        //Removing validation error
        inputCmp.setCustomValidity(""); // if there was a custom error before, reset it
        returnvalue = this.datevalue;
    }
    inputCmp.reportValidity(); // Tells lightning-input to show the error right away without needing interaction

    return returnvalue; // returning inputvalu