Add validation error to specific field using apex | sObject error methods

Telegram logo Join our Telegram Channel

Hello Trailblazer! Today we will discuss the brand new methods in the sObject.

The first method is the addError(), previously this method did not support adding validation to a field dynamically. The old code looked like below.

opportunity.Amount.adderror('Amount cannot be less than 5000.');

In the above code, we added validation to the Amount field of an Opportunity. But what if you don't know the field at compile time? Especially if you are working with a managed package sometimes you want to give the ability to decide this field at a run time. 

That problem is solved by the new version of addError() method.

add validation to specific field dynamically using apex

addError() use case

Let's assume you have some field validations configured in the custom metadata. Based on some conditions you decide which field to validate at run time. This is a very common scenario for Managed-Packages where each customer can have a different field for some purpose.

Sample Code

String dynamicallyValidatedField = /*Read from metadata*/

for(Opportunity opp: newList){
    if(opp.get(dynamicallyValidatedField) > 1000){
        opp.addError(dynamicallyValidatedField, 'Value of ' + dynamicallyValidatedField + ' can\'t be greater than 1000');

getErrors(), hasErrors() methods

These methods let you check and get errors from the records even before they are inserted into the database. These methods are designed to write test cases that run faster and without touching the database. 

Let's say, the example we saw above is inside a function, which sets the errors and returns the records. In test methods, you can test this method without even inserting the records in the database.

Sample Code

for(Opportunity opp: newList){
    if(opp.get('Amount') > 1000){
        opp.addError('Amount', 'Value of Amount can\'t be greater than 1000');

for(Opportunity opp: newList){

Other posts about winter 2021

Send Custom Notification using apex | Salesforce | Messaging.CustomNotification
Avoid null pointer exception with Safe Navigation Operator Apex


Learn MOAR with Winter ’21: Safe Navigation in Apex
All fields in SObject Class

No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at