+ Start a Discussion
Ankit Khiwansara 10Ankit Khiwansara 10 

Custom Validation for Email in Lightning Component

Hi Folks,
I am newbie on lightning and trying to learn custom validation on salesforce.
 
I want to validate email field value should only be rahul@gmail.com.For rest of the values , i want to populate error on component, but unable to do so. Could you please help me on that.
 
({
    newContactCreation: function (component, event, helper) {
        // Getting all fields and iterate them to check for validity
        var allValid = component.find('formFieldToValidate').reduce(function (validSoFar, inputCmp) {
            // Show help message if single field is invalid
            inputCmp.showHelpMessageIfInvalid();
            // Get the name of each field
            var name = inputCmp.get('v.name');
            // Check if name is emailField
            if (name == 'emailField') {
                // Getting the value of that field
                var value = inputCmp.get('v.value');
                // If value is not equal to rahul@gmail.com, add custom validation
                if (value != 'rahul@gmail.com') {
                    // Focus on that field to make custom validation work
                    //inputCmp.focus();
                    // Setting the custom validation
                    inputCmp.set('v.validity', { valid: false, badInput: true });
                    inputCmp.showHelpMessageIfInvalid();
                }
            }
            // Returning the final result of validations
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);

        if (allValid) {
            var action = component.get("c.createContact");
            action.setParams({
                con: component.get("v.con"),
                accountId: component.get("v.accountId")
            });

            action.setCallback(this, function (response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    windows.location.reload();
                } else {
                    alert("Problem in Data Fetching");
                }
            });

            $A.enqueueAction(action);
        }
    }
});



 
<aura:component controller="ElevenLCController">
    <aura:attribute name="accountId" type="String" />
    <aura:attribute name="con" type="Contact" default="{'Sobject' : 'Contact',
'FirstName' :'',
'LastNmae':'',
'Email':'',
'Phone':''}" />
    <div class="slds-p-around_x-small">
        <lightning:input required="true" aura:id="formFieldToValidate" label="First Name" value="{!v.con.FirstName}"
            type="text" messageWhenValueMissing="Please Enter First Name" />
        <lightning:input required="true" aura:id="formFieldToValidate" label="Last Name" value="{!v.con.LastName}"
            type="text" messageWhenValueMissing="Please Enter Last Name" />
        <lightning:input required="true" aura:id="formFieldToValidate" name="emailField" label="Email"
            value="{!v.con.Email}" type="Email" messageWhenBadInput="Enter Valid Email Id"
            messageWhenValueMissing="Please Enter Email" />
        <lightning:input required="true" aura:id="formFieldToValidate" label="Phone" value="{!v.con.Phone}"
            type="tel" />
    </div>
    <br />
    <lightning:button variant="brand" label="Create Contact" onclick="{!c.newContactCreation}" />
</aura:component>
Deepali KulshresthaDeepali Kulshrestha
Hi Ankit,

Please follow the given below code with the help of these, you can solve your problem, it may be helpful to you.

Custom Email Field Validation in Salesforce Lightning Component:
<aura:component >
    <aura:attribute name="oLead" type="Lead" default="{ 'sobjectType': 'Lead' }"/>
    <div class="slds-m-around--xx-large">
        <div class="slds-form--stacked">
            <div class="slds-form-element">
                <div class="slds-form-element__control">
                    <ui:inputText aura:id="leadEMail" label="Email" value="{!v.oLead.Email}" placeholder="abc@email.com..." class="slds-input"/>
                </div>
            </div>
            <div class="slds-m-around--medium">
                <button class="slds-button slds-button--brand" onclick="{!c.validateEmail}">Validate Email</button>
            </div>
        </div>
    </div>
</aura:component>

Lightning Controller :
({
    validateEmail : function(c, e, h) {
        try{
            let isValidEmail = true;
            let emailField = c.find("leadEMail");
            let emailFieldValue = emailField.get("v.value");
            let regExpEmailformat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if(!$A.util.isEmpty(emailFieldValue)){   
                if(emailFieldValue.match(regExpEmailformat)){
                  console.log('Your Email is valid');
                  emailField.set("v.errors", [{message: null}]);
                  $A.util.removeClass(emailField, 'slds-has-error');
                  isValidEmail = true;
                  c.find("leadEMail").set('v.value',null);
            }else{
                 $A.util.addClass(emailField, 'slds-has-error');
                 emailField.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);
                 isValidEmail = false;
            }
           }
           if(isValidEmail){
             // code write here..if Email Address is valid. 
           }
        }catch(e){
            console.log('Error>>>'+e);
        }
    },
})

Lightning App:

<aura:application extends="force:slds">
    <c:TestYA/>
</aura:application>

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha