Before Insert Validation in Salesforce Trigger [With Examples]

In Salesforce, users can sometimes create duplicate or invalid records. This can cause data duplication and confusion. To prevent this, we need to add a Before Insert Validation using a Salesforce Trigger, so that the record is checked before it is saved in the database.

For example, when a new Account record is created, we want to check if the Account Name already exists in Salesforce. If it does, we should stop the insert and show an error message to the user.

In this article, we will learn how to use before insert validation in Salesforce Trigger to prevent invalid or duplicate records from being saved in the database.

Before Insert Validation in Salesforce Trigger

A Before Trigger in Salesforce runs before the record is saved into the database.
It is mainly used to validate data or update field values on the same record before it is committed.

It is mainly used when:

  • You want to validate data (e.g., prevent wrong values from being saved).
  • You want to update fields on the same record before saving.
  • You need to set default values automatically.

Now, let’s understand how to write a trigger helper and a handler class to prevent users from creating duplicate records in Salesforce.

For example, we want to prevent the creation of duplicate accounts whose names already exist in the account object. That means a user will only be able to create a duplicate account record.

We can say that if there is at least one account name that matches the account being created, Salesforce will prevent deletion to protect an important record.

Helper Class: Implement Logic to Check Before Insert Validation in Salesforce

A trigger helper class is simply an Apex class that creates different methods and implements the business logic required to achieve our desired outcome. Instead of writing all the logic directly inside the trigger, we keep it in the helper class.

First, we will create a helper class to implement the logic that prevents duplicate account name records.

To create the class, go to Setup → Developer Console -> File -> New -> Apex Classes → and then write the Apex class with the required logic.

In the helper class, I have created a method that implements the logic, and this method will be called in the trigger, making the trigger cleaner and easier to understand.

In the method, I declared a list collection that gets the newly created records from the trigger, and then we use this List to check for duplicate records in Salesforce.

After that, we use a for loop to iterate over the Account records stored in the list. To get only unique records, we then store them in a Set collection.

Then, using a Map collection, we mapped the Account Name to the corresponding Account record in Salesforce, which we retrieved using a SOQL query. That means we are creating a key-value pair, where:

  • Key = Account Name.
  • Value = Account record itself.

This way, we can easily search if the new Account name already exists. If it already exists, we use the addError() method to display an error and prevent the account record from being inserted into the account object.

public class AccountTriggerHandler {
    
    public static void preventDuplicateAccounts(List<Account> newAccounts){
        Set<String> accountNames = new Set<String>();
        
        for(Account acc : newAccounts){
            if(String.isNotBlank(acc.Name)){
                accountNames.add(acc.Name.trim().toLowerCase());
            }
        }
        
        Map<String, Account> existingAccounts = new Map<String, Account>();
        for(Account acc : [SELECT Id, Name FROM Account WHERE Name IN :accountNames]){
            existingAccounts.put(acc.Name.trim().toLowerCase(), acc);
        }
        
        for(Account acc : newAccounts){
            if(existingAccounts.containsKey(acc.Name.trim().toLowerCase())){
                acc.addError('An Account with this Name already exists: ' + acc.Name);
            }
        }
    }
}
Create Trigger Helper Class in Salesforce Apex

Trigger: Call Method Declared in Helper Class in Salesforce

This class includes methods for various trigger events, such as ‘before insert’ and ‘after update’, and processes the logic relevant to each event. Then the trigger class calls the helper class methods when an Account is being deleted.

Create an Apex Trigger with a Name and select the Object on which you want to create the trigger from the drop-down menu of sObject.

Here, I added an if condition to check whether, using the context variable, we are calling events, which are isBefore and isInsert. Then, using the helper class name, call the methods in the order you want to execute.

trigger AccountTrigger on Account (before insert) {

    if (Trigger.isBefore && Trigger.isInsert){
        AccountTriggerHandler.preventDuplicateAccounts(Trigger.new);
    }
}
Create Before Insert Validation in Salesforce Trigger

Proof of Concept

Now, navigate to the Apex Triggers from Setup. For that, search for the Apex Trigger in the Quick Find box, and there you will see the trigger Name and Status

If the status is Active, then it will work. Otherwise, the trigger will not automate the process of preventing duplicate account records with the same name from being inserted.

Check Apex Trigger Active Status in Salesforce Lightning

In the screenshot below, you can see we have an existing Account record named TSinfo Technologies. Now, let’s verify that our trigger prevents the creation of another Account with the same name.

Create Salesforce Account Object Record

Now, when I create a new Account record with the same name as the existing one and click the Save button, you can see that Salesforce displays an error message and prevents the duplicate record from being saved.

This message we received because of the Before Insert validation logic written in the trigger, which checks for duplicate Account names before saving the record.

Before Insert Validation in Salesforce Trigger

In this way, we can utilize before-insert validation in a Salesforce trigger to validate records before they are inserted into the Salesforce database.

Conclusion

I hope you have an idea about how before-insert validation works in Salesforce Triggers, and how we can use a helper class to keep the trigger clean and easy to maintain.

In this article, we created a helper class method to check for duplicate Account names and called it inside the trigger. We also tested it by creating a new Account with an existing name and verified that Salesforce blocked the duplicate record with an error message.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.