function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lauren BLauren B 

Custom message validation on the submit button.


I have build a form in lightning aura component. My requirement is how to validate onclick custom message to check email duplicacy on the submit button. In my code message for email duplicacy is showing but upon clicking the submit button it is getting submitted without changing the email.
HTML-

<lightning:input  class="inputfields"    aura:id="email" label="Email" type="Email" name="email" value="{!v.newContact.Email}" required="true" messageWhenValueMissing="Please enter your Email"  pattern="^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$"  messageWhenPatternMismatch="Please Enter a valid Email Address" onchange="{!c.handleOnChangeEmail}"/>

JS-

handleOnChangeEmail:function(component, event, helper) {
    var action=component.get("c.getEmails");
    action.setParams({
        "emailstring":component.get("v.newContact.Email")
    });     
    action.setCallback(this, function(response) {
        var state= response.getState();
        if(state==='SUCCESS'){
            var email = component.find("email");
            if (response.getReturnValue() === "Email already exists") {
                email.setCustomValidity("Email already exists");
            } else {
                email.setCustomValidity(""); // if there was a custom error before, reset it
                 
            }
            email.reportValidity(); // Tells lightning:input to show the error right away without needing interaction
        }});
    $A.enqueueAction(action);            
},


Submit Button-

SubmitPage:function(component, event, helper) { 
    

var firstname = component.get('v.newContact.FirstName');
    var regex=/^[a-zA-Z ]+$/;
    var validFirstName = regex.test(firstname);
    
    var lastname = component.get('v.newContact.LastName');
    var regex=/^[a-zA-Z -]+$/;
    var validLastName = regex.test(lastname);
    
    var phones = component.get('v.newContact.Phone');
    var regex=/^[-0-9() ]+$/;
    var validPhone = regex.test(phones);
    
    var email = component.get('v.newContact.Email');
    var regex=/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
    var validEmail = regex.test(email);

 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Amy,

Can you try the below link that has a controller that validates email instead of checking for the pattern you can try checking if the email already exists below is the controller code in the link [https://salesforcescool.blogspot.com/2018/12/email-field-validation-in-lightning.html]:

Controller:
({
    ValidateEmail : function(component, event, helper) {  
        var emailField = component.find("txtEmail");
        var emailFieldValue = emailField.get("v.value");
        // Store Regular Expression
        var 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,}))$/;  
        // check if Email field in not blank,
        // and if Email field value is valid then set error message to null, and remove error CSS class.
        // ELSE if Email field value is invalid then add Error Style Css Class, and set the error Message.          
        if(!$A.util.isEmpty(emailFieldValue)){   
            if(emailFieldValue.match(regExpEmailformat)){
                emailField.set("v.errors", [{message: null}]);
                $A.util.removeClass(emailField, 'slds-has-error');                
            }else{
                $A.util.addClass(emailField, 'slds-has-error');
                emailField.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);               
            }
        } 
    },
 })

Similar implementation in stackexchange: https://salesforce.stackexchange.com/questions/238047/duplicate-record-error-using-lightningrecordeditform

I hope this helps and in case if this comes in handy can you please choose this as the best answer so that it can be useful for others in the future.

Regards,
Anutej