Most examples I've seen for Lightning form validation assign a common aura:id to all field components in the form, and then use component.find to return the set of components to validate, as in this common code fragment:

var allValid = component.find('someId').reduce(function (validFields, inputCmp) {
    return validFields && inputCmp.get('v.validity').valid;

This approach seems to preclude what I'd think would be a typical use of aura:id -- to uniquely identify a component so it can be accessed individually. The fact that component.find returns either a single element or an array suggests that the designers expected both kinds of uses.

What, then, is an appropriate way to be able to do that "bulk" validation, or any other iteration through field components, while still being able to access them individually?


You can do something like this:

// Array of field aura:id values
var auraIds = ['fieldXyz', 'fieldAbc', ...];

var allValid = auraIds.reduce(function(validFields, auraId) {
    // Find component corresponding to the aura:id
    var inputCmp = component.find(auraId);
    return validFields && inputCmp.get('v.validity').valid;

or if in the same function you also want to access them individually:

var fieldXyzCmp = component.find('fieldXyz');
var fieldAbcCmp = component.find('fieldAbc');

var cmps = [fieldXyzCmp, fieldAbcCmp, ...];

var allValid = cmps.reduce(function(validFields, inputCmp) {
    return validFields && inputCmp.get('v.validity').valid;
|improve this answer|||||
  • That's the approach I was considering... thanks for the validation! The use of a common ID for grouping is so ubiquitous in the tutorials that it seemed odd to go another way. I wonder if it might have been a convenience for the purposes of the tutorials that just turned into a common practice. – Jeff Garbers Jun 18 '18 at 17:14
  • 1
    @JeffGarbers And it is not even a safe example as the code will fail when there is only one field or if there are no fields thanks to the crazy semantics of component.find. – Keith C Jun 18 '18 at 17:16

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.