Sub topic 6
Custom validation rules after before triggers
This chapter assumes you can write a basic Apex trigger and a validation rule formula. It also assumes you know that a save runs as one transaction. The earlier chapters covered before-save flows and before triggers. This one covers what happens right after them.
Where validation sits in the order
Validation runs twice in a save. The first pass checks system rules, such as field types and maximum lengths, before any before-save flow or trigger runs. After the before-save flows and before triggers finish, Salesforce runs most system validation again. Then it runs your custom validation rules.
Because of this order, custom validation rules see the record as the before-save flows and before triggers left it. They do not see the values the user originally submitted.
What this ordering lets you do
A before trigger can normalize data so that a validation rule accepts it. The user can type a phone number as (415) 555-0100. The trigger strips the punctuation, and the rule then checks the cleaned value.
The same ordering can also work against you. A before trigger can write a value that breaks a validation rule, even when the user entered valid data. The error then appears on a field the user never edited.
Worked example
Create a validation rule on Account named Phone_Is_Ten_Digits. Its error condition formula is:
AND(
NOT(ISBLANK(Phone)),
NOT(REGEX(Phone, "\\d{10}"))
)The rule fails any non-blank phone that is not exactly ten digits. Now add a trigger that cleans the value first:
trigger AccountPhoneCleanup on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (a.Phone != null) {
a.Phone = a.Phone.replaceAll('[^0-9]', '');
}
}
}This test shows both outcomes. It assumes the validation rule above is active in the org.
@IsTest
private class AccountPhoneValidationTest {
@IsTest
static void formattedPhonePassesAfterCleanup() {
Account a = new Account(Name = 'Formatted', Phone = '(415) 555-0100');
Database.SaveResult sr = Database.insert(a, false);
System.assert(sr.isSuccess(), 'Trigger should clean the phone before validation');
System.assertEquals('4155550100', [SELECT Phone FROM Account WHERE Id = :a.Id].Phone);
}
@IsTest
static void shortPhoneFailsValidation() {
Account a = new Account(Name = 'Short', Phone = '123');
Database.SaveResult sr = Database.insert(a, false);
System.assert(!sr.isSuccess());
System.assertEquals(
StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION,
sr.getErrors()[0].getStatusCode()
);
}
}Without the trigger, the first test would fail. The rule would see the raw string with punctuation and reject it.
Behavior to know
- Final values are validated. Rules evaluate the record after before-save flows and before triggers. Debug the final values, not the input.
- After triggers never see failures. A record that fails validation never reaches the save step. Its after triggers do not run.
- Failure rolls back the transaction. With
allOrNoneset to true (the default for plain DML statements), one failing record rolls back the whole batch. WithDatabase.insert(records, false), only the failing records are rejected. Passing records continue. - Rules do not run on delete. Validation rules apply to inserts and updates.
- Workflow re-fire does not re-run them. If a workflow field update changes the record, before and after update triggers fire once more. Custom validation rules do not run again for that second pass. A value written by the field update is therefore not checked against your rules.
- Duplicate rules come next. They run only after custom validation passes.
Do not rely on validation rules alone to protect data written by after triggers or later automation. Those writes happen after validation has already run for the original save. They trigger their own validation only if they are separate DML operations on a record.
Choosing between a validation rule and addError
You can also reject a record from a before trigger with addError. Both approaches block the save and show a message. They differ in these ways:
| Concern | Validation rule | `addError` in a before trigger |
|---|---|---|
| Maintained by | Admins, no code | Developers |
| Sees trigger-modified values | Yes | Only if it runs after the code that changes them |
| Can query other records | Limited to formula fields and related fields | Any SOQL, within governor limits |
| Runs on bulk data | Yes | Yes, if the loop is bulk-safe |
Prefer a validation rule when a formula can express the condition. Use addError when the check needs a query or logic a formula cannot express.
Exercise
A before insert trigger sets Status__c to 'Active'. A validation rule on the same object fails when Status__c = 'Active' and Approver__c is blank. A user creates a record and leaves both fields empty. Does the save succeed, and do the after insert triggers run?
Show answer
The save fails. The before trigger sets Status__c to 'Active', and then the validation rule runs against that final value. Approver__c is blank, so the rule rejects the record. The save step is never reached, so the after insert triggers do not run, and the transaction is rolled back.