[SalesForce] Child component validation on Parent Component’s Save

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?

Best Answer

If you dont want to use aura methods, The only other clean solution i can think of is using events:

  1. You can use an application event in parent which will get fired it its children.
  2. The child components will listen to it and do the validation and fire a component event back to parent to confirm if validation is successful.
  3. The parent can listen to this component event and based on the response from children can take the next course of action save or not save