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
SandeepbvSandeepbv 

Validation on Account when upserting record

Hello,

I want to add Validation on account object when upserting new records. Please suggest how it can be done.

First, I want to check whether that record exists using "key" field(unique).If it exists, and the record has different email than what we have in our record; the system should throw an error with some message.

Second, I want to do same validation as in step 1, but this time with email. When upserting, if the record has same email and different key than what we have in our existing record; the system should not allow the upsert.
Ahmad J. KoubeissyAhmad J. Koubeissy
Try this code:
 
trigger accountTrigger on Account(before insert, before update){
	set<string> AccKey = new set<string>();
	set<string> AccEmail = new set<string>();
	map<string,string> mapkeytoemail = new map<string,string>();
	map<string,string> mapemailtokey = new map<string,string>();
	set<string> accountskey = new set<string>() ;
	set<string> accountsEmail = new set<string>() ;
	
	for(account acc:trigger.new){
	  AccKey.add(acc.key__c);//replace key__c with your field allover the code
	  AccEmail.add(acc.email__c);//replace email__c with your field allover the code
	}
	for(account acc: [select id,key__c,email__c from account where (email__c in :AccEmail) or (key__c in :AccKey)]){
	    mapkeytoemail.put(acc.key__c,acc.email__c);
	    mapemailtokey.put(acc.email__c,acc.key__c);
	    accountskey.add(acc.key__c);
	    accountsEmail.add(acc.email__c);
	}
	for(account acc:trigger.new){
	    //first case
	    if(accountskey.contains(acc.key__c)){
	        if(acc.email__c != mapkeytoemail.get(acc.key__c)){
	            acc.addError('some message');
	        }
	    }//Second case
	    if(accountsEmail.contains(acc.email__c)){
	        if(acc.key__c!= mapemailtokey.get(acc.email__c)){
	            acc.addError('some message');
	        }
	    }
	}
}

Dont forget to mark as Best Answer if this solves your problem. Thank you !!