[SalesForce] Custom field validation using lightning:recordEditForm

how can we do custom validation on fields in recordEditForm component (using inputfield) and stop the record getting saved.

Sample Code:

–cmp-

<lightning:recordEditForm aura:id="editLineItem" recordId="003W000000o0DRyIAM" objectApiName="Contact"  onsubmit="{!c.saveRecord}" onsuccess="{!c.recordSaved}" onerror="{!c.errorInformation}" >
<lightning:messages />
                <lightning:layout multipleRows="true">
                        <lightning:layoutItem size="6" padding="around-small">
                            <lightning:inputField aura:Id='inputCmp' fieldName="Name"/>

                        </lightning:layoutItem>
<lightning:button aura:id="saveOrder" label="Save Order"  variant="brand"  type='submit' onclick="{!c.handlefieldValidation}"/>
</lightning:layout>                
</lightning:recordEditForm>

-cmp-ends

controller–

({
    myAction : function(component, event, helper) {

    },

    handlefieldValidation : function(component, event, helper) {
        console.log('do Field Validations');
        helper.validateFieldValues(component,event);
    },

    saveRecord: function(component, event, helper) {
        console.log('Inside saveRecord');

    },
    recordSaved: function(component, event, helper) {
        console.log('Inside recordSaved');

    },

    errorInformation : function(component, event, helper) {
        console.log('Inside Error handling');
        var eventName = event.getName();
        var eventDetails = event.getParam("error");
        console.log('Error Event received' + eventName);


    },
})

–helper–

({
    helperMethod : function() {

    },

    validateFieldValues : function(component,event) {

             console.log('Inside validation module');
                var comp = component.find("editLineItem");
                $A.util.addClass(comp,'slds-has-error');
                comp.set("v.error", [{message:"Input not a number: "}]);
                event.pause();
                console.log('post event pause');

    },
})

Best Answer

A simple approach to validate field validity on lightning:inputField elements is by using built-in Lightning Component methods.

Component:

<lightning:recordEditForm
                          aura:id="form"
                          objectApiName="Account">
    <lightning:inputField
                          aura:id="field"
                          required="true"
                          fieldName="Name"/>
</lightning:recordEditForm>
<lightning:button label="Save" onclick="{!c.handleSave}"/>

Controller:

handleSave : function(component, event, helper) {
    // Make sure fields are in an iterable object by casting to array if not already
    let fields = component.find("field");
    if (fields) {
        fields = Array.isArray(fields) ? fields : [fields];
    }
    else {
        fields = [];
    }
    const valid = fields.reduce((validSoFar, field) => {
        // Return whether all fields up to this point are valid and whether current field is valid
        // reportValidity returns validity and also displays/clear message on element based on validity
        return (validSoFar && field.reportValidity());
    }, true);
    // If all fields aren't validated, throw error message
    if (!valid) {
        const toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "message": "Review all error messages below to correct your data.",
            "type": "error"
        });
        toastEvent.fire();
    }
    // Otherwise submit save
    else {
        component.find("form").submit();
    }
}
Related Topic