0

I am using the following piece of code to display required error message

    var allValid = component.find('smaField').reduce(function (validSoFar, inputCmp) {
        inputCmp.showHelpMessageIfInvalid();
        return validSoFar && inputCmp.get('v.validity').valid;
     }, true);
    if(allValid){
         helper.savePortfolioDetailsHelper(component, event, helper);
    }

My problem with the above is that, it is only working where there are more than once element in the array.

i.e. there is more than one required field. If the page has only one lightning input which is required having aura:id smaField, it is not working. I would like to understand why that is, and is there any way to fix it.

  • That's because the component.find would return an object and not an array if only one component is found. Which is the reason why your .reduce function would not work. You need to handle that separately. – Sam Apr 22 '19 at 11:00
2

This is all fine, there is a trick which is very much hidden in the documentation:

Here is what the documentation says: find documentation

So we can handle this with concat method of array:

var rows = c.find('smaField');
var elements = [].concat(rows || []);
/* Now here the elements will always be an array, and won't break your code anymore. */

Copied from https://salesforce.stackexchange.com/a/253859/29734

|improve this answer|||||
0

You can use a simple if block to check if object returned by component.find is an array or not. If array is returned, then use the reduce function to check validity of individual elements. If not array, i.e. a single element, then do the validation directly without using any array function which in your case is reduce. Refer this question to check if an object is array or not. https://stackoverflow.com/q/4775722/4983575

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.