+ 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
            // 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
                    // Setting the custom validation
                    inputCmp.set('v.validity', { valid: false, badInput: true });
            // Returning the final result of validations
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);

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

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


<aura:component controller="ElevenLCController">
    <aura:attribute name="accountId" type="String" />
    <aura:attribute name="con" type="Contact" default="{'Sobject' : 'Contact',
'FirstName' :'',
'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" />
    <br />
    <lightning:button variant="brand" label="Create Contact" onclick="{!c.newContactCreation}" />
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 class="slds-m-around--medium">
                <button class="slds-button slds-button--brand" onclick="{!c.validateEmail}">Validate Email</button>

Lightning Controller :
    validateEmail : function(c, e, h) {
            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,}))$/;
                  console.log('Your Email is valid');
                  emailField.set("v.errors", [{message: null}]);
                  $A.util.removeClass(emailField, 'slds-has-error');
                  isValidEmail = true;
                 $A.util.addClass(emailField, 'slds-has-error');
                 emailField.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);
                 isValidEmail = false;
             // code write here..if Email Address is valid. 

Lightning App:

<aura:application extends="force:slds">

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