[SalesForce] lightning-input-field Error in $A.getCallback() [t.checkValidity is not a function]

I have a requirement to build a custom layout in LWC, and for that I am using lighting-record-edit-form and lightning-input-field with the required attribute.

When the user tries to submit the form on the click of a button, I need to validate and check if the required fields have been filled up.

I tried to use the following code for the same,

const allValid = [...this.template.querySelectorAll('lightning-input-field')]

       .reduce((validSoFar, inputCmp) => {

           inputCmp.reportValidity();

           return validSoFar && inputCmp.checkValidity();

       }, true);

but I am getting an error when I click the button, "Error in $A.getCallback() [t.checkValidity is not a function]"

This piece of code works fine if I try to use lightning-input instead of lightning-input-field. The need to use lightning-input-field arises as there are some lookup fields that I need to render on the form.

Would anyone happen to know how can I validate the required fields successfully, and throw an error accordingly for lightning-input-field?

Best Answer

Okay, so the reason it is working with lightning-input but not with lightning-input-field is that the checkValidity() function is not available for lightning-input-field.

lightning-input: https://developer.salesforce.com/docs/component-library/bundle/lightning-input/specification

lightning-input-field: https://developer.salesforce.com/docs/component-library/bundle/lightning-input-field/specification

If i undestood the problem correctly reading the other comments, you want to mark as red(incomplete) the fields but the required attribute only makes it on the onblur event of the field.

if this is the problem you can mark as required the fields and then make a validate function that calls the reportValidity() function on the lightning-input-field element to mark it as incomplete (as it will check that the field is required but it is not filled).

An example:

validateFields() {

    let i;
    var formFields = Array.from(this.template.querySelectorAll('lightning-input-field'));

    for (i = 0; i < formFields.length; i++) {
        formFields[i].reportValidity();
    }
}