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

    var allValid = component.find('smaField').reduce(function (validSoFar, inputCmp) {
        return validSoFar && inputCmp.get('v.validity').valid;
     }, true);
         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, 2019 at 11:00

2 Answers 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


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

You must log in to answer this question.

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