[SalesForce] Custom validity does not work when component is recovered in array

I am trying to create a dynamic form validation using the lightning:input component.

According to the documentation of this component (https://developer.salesforce.com/docs/component-library/bundle/lightning:input/documentation), to set a custom error, I have to use the setCustomValidity() method, but the component will continue to present the custom error until I pass an empty string in this same method.

In order to reevaluate the form after a first submit that gone wrong, I must clean the custom error from all fields. To do so, I use the following function in helper:

reevaluateFields : function(component) {
        // get all the elements of the form
        var elements = component.find('taskFormElement');

        //iterate the elements
        for(var i = 0; i < elements.length; i++) {
            // clean the field's custom error
            elements[i].setCustomValidity('');
            // function to reevaluate the field's validity 
            elements[i].reportValidity();
        }
    },

In theory this should work like a charm, but in practice the system throws an error: "elements[i].setCustomValidity is not a function". And this error happens only when the "component.get()" returns an array, because when it returns only one component, the setCustomValidity() function works perfectly.

Does anyone knows if it is possible to make this work, and how I could do so?

Best Answer

You can try a different way of clearing the lightning:input error message

reevaluateFields : function(component) {
        // get all the elements of the form
        var elements = component.find('taskFormElement');

        //iterate the elements
        for(var i = 0; i < elements.length; i++) {
            // clean the field's custom error
            elements[i].set('v.validity', {valid:true, badInput :false});
            // function to reevaluate the field's validity 
            elements[i].showHelpMessageIfInvalid();
        }
    }

Source: https://salesforce.stackexchange.com/a/184718/19118

Related Topic