Check that criteria are met in a before insert trigger

I want to check whether a certain criteria is met or not using a trigger before inserting a record. if it meets the criteria, i insert the record, but if it does not i want to display an error message that it doesn’t meet the criteria. how do i do it?
Please help if anyone knows.


You can use the addError method on the SObject for this, the Trigger Exceptions topic of the Apex Developers guide starts to describe the process and links to other topics describing this approach.

Marks a record with a custom error message and prevents any DML operation from occurring.

Note that you can also apply the addError method call to a field, as well. This will also block the insert of the record and provide the user with more context of what field value is causing the issue.[0].myField__C.addError(‘bad’);

Here is sample showing the difference between record level and field level use of addError

trigger TestTrigger on Test__c (before insert) {

    for(Test__c record :
            record.addError('Cannot have the word Bad in the record Name');
        if(record.A_Number__c != 42)
            record.A_Number__c.addError('You have not provided the answer to life the universe and everything!');

enter image description here

enter image description here

Security Note: If you worried about other Apex Triggers being added to your object and changing the values of your fields. You should consider performing the validation in the after phase of the trigger since only then can you ensure no further changes will be made to your fields, by the user or other Apex Triggers added by the customer (if your developing a packaged solution) or other developers.

Update: I have since written a blog on the practice of considering validation in the after phase of your trigger.

Source : Link , Question Author : Sam , Answer Author : Bahman.A

Leave a Comment