Validation rule in apex trigger

Salesforce provides validation rules in configuration for standard and custom objects. sometimes the requirements may not be fulfilled using validation rule, especially when the validation criteria is very complex or need querying in database to check previously created data. In such a case we can write validation logic in trigger.

In this article, I will demonstrate how to write validation logic in apex trigger.

Here in below example, there is before insert and before update trigger on Opportunity object. In this trigger the amount field has validated, for less than 5000.

trigger TriggerOpportunity on Opportunity (before insert, before update){
    for(Opportunity opp:trigger.new){
        if(opp.Amount < 5000){
            opp.Amount.adderror('Amount cannot be less than 5000.');
        }
    }
}

download