My Lightning component structure is as follows
<c:ParentComponent>
<aura:iteration>
<c:childComponent />
</aura:iteration>
<ui:button label="Save" press="{!c.validateAndSave}"/>
</c:ParentComponent>
Child component has a lot of validations. These validations would fire on 'blur' event of input* fields (say inputNumber) fields in child component. One of them is given below.
generalValidation : function(component, event, helper){
var changedFieldId = event.getSource().getLocalId();
var changedFieldCmp = component.find(changedFieldId);
var enteredValue = changedFieldCmp.get("v.value");
//--Check for -ve entry
if(enteredValue < 0){
changedFieldCmp.set("v.errors", [{message: $A.get('$Label.c.twod_value_cannot_be_negative')}]);
return false;
}
return true;
}
Similarly, based on business conditions there are more. I didn't want to make this validation function bulk.
Parent Component has a 'Save' button. On click of it, it has to validate all child components again.
How can I achieve that?
Methods I have tried is to create an empty object and pass it onto child component. Whenever there's an error, I would update the same. Again, on Save, I will check for any errors in the object and prevent submission. Little complicated but works!
Alternatively, I could have an error counter attribute on parent. This will be incremented whenever there's an error. This approach is complicated too.
Keeping same aura:Id and checking for validity is also not an option in my case. So is exposing child methods to parent and calling them on Save.
Do you have any other unique way?