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
shoba shobashoba shoba 

Using trigger,Preventing duplicate email ID in lead

I have a created two custom fields in lead called Alternate email1, Alternate email2 .

My scenario is to show an alert message for the duplicate email while inserting or updating the record.  For e.g. if X@gmail.com exist in EmailID(Standard field)  in  a lead then it should not be allowed to be entered as Email or alternate email ids(Custom field)  of other lead and the vice versa.
At the same time while inserting the record in lead , the email id mention in Email,Alternate email1, Alternate email2 field should be different otherwise it should through an alert message.
Can anyone help me out to solve this.

trigger leadDuplicate on Lead (before insert, before update) {

Map<String, Lead> leadMap = new Map<String, Lead>();

for (Lead lead : System.Trigger.new) {

if ((lead.Email != null) &&

    (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) {

if ((leadMap.containsKey(lead.Email)) || (leadMap.containsKey(lead.Alternate_Email1__c)) || (leadMap.containsKey(lead.Alternate_Email_2__c))) {

  lead.Email.addError('Another new lead has the ' + 'same email address.');

} else { 

    leadMap.put(lead.Email, lead);
    leadMap.put(lead.Alternate_Email1__c, lead); 
    leadMap.put(lead.Alternate_Email_2__c, lead);  

}

}

}

for (Lead lead : [SELECT Email,Alternate_Email_2__c,Alternate_Email1__c FROM Lead
                  WHERE ((Email IN :leadMap.KeySet()) or (Alternate_Email_2__c IN :leadMap.KeySet()) or (Alternate_Email1__c IN :leadMap.KeySet()))] ) {

Lead newLead = leadMap.get(lead.Email);


Lead.Email.addError('A lead with this email ' + 'address already exists.');

}

}
Thanks In Advance
henryT.ax664henryT.ax664
You need to change your map to use the email address as the key.  Currently you are using the lead Id as your map key so 
Line 11 is not going to find an email address in leadMap.containsKey(...).