1

I have a simple lightning-record-form. At the time of submit, I need to validate if the values are valid because I am implementing a "save and add next" button that saves the current entry, clears the form and recordId, and redisplays the form for the next record to be entered.

Based on some googling I found this:

const inputFields = this.template.querySelectorAll('lightning-input');
console.log('found this many input fields: ' + inputFields.length);
for (const i=0;i<inputFields.length;i++) {
  inputFields[i].reportValidity();
  console.log('input is valid: ' + inputFields[i].checkValidity());
  isValid = isValid && inputFields[i].checkValidity();
}

However, the console log output says that no elements were found? What is the proper way to acquire the input fields and check the validity of the values? I need to do this so that I can prevent the submit from completing if the data is bad so that I can then show the user a toast message that they must correct the data before saving.

1 Answer 1

1

Hope you are doing good!

What I found from the lightning-record-form document is that the recportValidity() method is not available there. I suggest get the fields using below code and try to check and fire a custom validation using javascript code.

    handleSubmit(event){
        event.preventDefault();       // stop the form from submitting
        var foundError = false;
        const fields = event.detail.fields;
        if(!fields.LastName){
            foundError = true;
        }
        if(foundError)
            //Fire some error toast with custom error msg
        else
            this.template.querySelector('lightning-record-form').submit(fields);
 }

It is doable for small number of fields in the form but if your form contains a large number of fields then it will going to result in large number of lines in your code.

Let me know if this helps.

Thanks, Rohit Bhamdare

1
  • This was a workable solution since I only had 4 fields exposed. Thanks! Apr 20, 2021 at 18:17

You must log in to answer this question.

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