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
CBBsfdcCBBsfdc 

Write a trigger to validate duplicates on lead using email when new lead is created

Best Answer chosen by CBBsfdc
SandhyaSandhya (Salesforce Developers) 
Hi,

Below code works.
 
trigger leadDuplicatePreventer on Lead (before insert,after update) {
  list<lead> lead = new   list<lead>(); 
 for(lead a: trigger.new)
 {
lead=[select id,name,email from lead where email=:a.email];
  if(lead.size()>0)
  {
   a.email.adderror('email already exist');
  }
 }
}

Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya
 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi,

Below code works.
 
trigger leadDuplicatePreventer on Lead (before insert,after update) {
  list<lead> lead = new   list<lead>(); 
 for(lead a: trigger.new)
 {
lead=[select id,name,email from lead where email=:a.email];
  if(lead.size()>0)
  {
   a.email.adderror('email already exist');
  }
 }
}

Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya
 
This was selected as the best answer
Om PrakashOm Prakash
Hi,
I recommend to complete this trailhead module and you can write this trigger by own.
https://trailhead.salesforce.com/content/learn/modules/apex_triggers

Feel free to ask if any queries in your trigger
 
Vishal_GuptaVishal_Gupta
Hello,

There is no need of trigger for this, you can create a Duplicate Rule and it will work for you. Let me know if you need more help.

User-added image