Istock 1503735047.jpeg

Validating Email Already Exist in Database Using Apex

Database Using Apex: In this blog post, we are going to learn how we can apply custom validation in LWC to the Email field to make it unique. We’ll validate whether the Email is already exist in database or not.

Acceptance Criteria:  In an account creation form, create a custom validation on the Email field so that the user should not enter a duplicate email value. When the duplicate email is present, then show the error message.

To do this, here we’ve created a form using Lightning record edit form in our Lightning Web Component(LWC).  The form contains the Name field, Email field (which will be as Primary Contact Email on UI), and Submit button.

When the user enters the email address, it will validate with all the records in the org. If a duplicate email is found, the error message will be thrown.

Let’s get started…

Validating Email using Apex: –

emailUniqueComponent.Controller

public with sharing class EmailUniquenessClass 
     @AuraEnabled(cacheable=true)
    public static String getEmail(Id recordId)
      return [SELECT Email__c FROM Account WHERE Id=: recordId ].Email__c;  
    
    
    @AuraEnabled(cacheable=true)
    public static Boolean isEmailUnique(String email , Id recordId)
      List<Account> accReq = [SELECT Id FROM Account WHERE Email__c =:email AND Id !=: recordId ];  
        return accReq.isEmpty();
    

emailUniqueComponent.html

<template>
    <div class="slds-box box-config">
        <lightning-card>
            <lightning-record-edit-form object-api-name=Account_Object onsuccess= handleSuccess onerror=handleError>
                <div class="slds-grid" >
                <div class="slds-size_2-of-2 slds-grid slds-wrap slds-form_horizontal slds-form" >
                <lightning-input-field field-name=Name ></lightning-input-field>
                <lightning-input-field field-name=Email type="email" value=email onchange=handleEmailChange ></lightning-input-field>
                                            
                                                
            </div>
                </div>
            <lightning-button type="submit" variant="brand" label="Save Request" class="slds-align_absolute-center"></lightning-button>
        
            </lightning-record-edit-form>
        
        </lightning-card>

    </div>
</template>

emailUniqueComponent.js

import  LightningElement, wire, api  from 'lwc';
import ShowToastEvent from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name__c';
import EMAIL_FIELD from '@salesforce/schema/Account.Email__c';
import getEmail  from '@salesforce/apex/EmailUniquenessClass.getEmail';
import isEmailUnique  from '@salesforce/apex/EmailUniquenessClass.isEmailUnique';

export default class EmailUniqueComponent extends LightningElement {
    @api recordId;
    email;
//Map imported fields to HTML side
Account_Object = ACCOUNT_OBJECT;
Name = NAME_FIELD;
Email = EMAIL_FIELD;


//Email Unique Check
@wire(getEmail , recordId: '$recordId')
wiredEmail(error , data)
    if(data)
        this.email = data;
    
    else if(error)
        console.log(error);
    


handleEmailChange(event)
    const newEmail = event.target.value;
    isEmailUnique(email: newEmail , recordId: this.recordId)
    .then(result => 
        if(!result)
            console.log('Email wala error =>' ,!result)
            const toastEvent = new ShowToastEvent(
                title: 'Duplicate Email',
                message: 'The email value entered already exists. Please enter a unique email.' ,
                varient: 'error'
            );
            this.dispatchEvent(toastEvent);
            event.target.value = this.email;
        
    )
    .catch(error => 
        console.log(error);
    );

}

emailUniqueComponent.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

To validate the Email field, we first created the controller containing two methods getEmail and isEmailUnique. Then, imported those methods in the JS and used them in the wire method and handler event for validating the email address and throwing an error message if a duplicate was found.

Result:

Img1

When the user enters the required details and the email address, the “handleEmailChange” handler will automatically check all the email addresses present in the org/database.

If the duplicate mail ID is present, it will throw an error message along with the title “Duplicate Email” with the help of “ShowToastEvent”.

You can see the error message popping up in the above picture when the duplicate email ID is present.

In this way, we can validate the mail address and make it unique. Database Using Apex

Scroll to Top
Call Now Button