How to validate data before saving in lighting:recordForm?

Component:

<aura:component implements="force:appHostable" >

    <div class="slds-box slds-theme_default">        
        <lightning:recordForm recordId="001f200001XrzFQAAZ" 
                              objectApiName="Account"
                              layoutType="Full" 
                              mode="Edit" 
                              onsubmit="{!c.saveRec}"/>        
    </div>
    
</aura:component>

Controller:

({
saveRec : function(component, event, helper) {
        var eventFields = event.getParam("fields");
        var field = 'NumberOfEmployees';
        if (eventFields.hasOwnProperty(field)) {
            if ( !eventFields.NumberOfEmployees ) {            
                event.preventDefault();
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Error!!!",
                    "message": "Please fill Employees field",
                    "type": "error"
                });
                toastEvent.fire();
            }
        }
}
})

Output:


3 comments:

  1. You're awesome!!!!!!!!!! thank you

    ReplyDelete
  2. How would you implement this for more than one field, say maybe for "NumberOfEmployees" and "Industry"?

    ReplyDelete
    Replies
    1. Use if (eventFields.hasOwnProperty('Industry')). Similarly for other fields.

      Delete