Sub topic 15
When to use flows or Apex instead
This chapter assumes you can write an error condition formula, know that validation rules run when a record is saved, and know roughly where they sit in the order of execution. Here you will learn where a validation rule stops being the right tool, and what to use in its place.
What validation rules do well
A validation rule evaluates one formula against the one record being saved. It has no code to deploy, administrators can maintain it, and it shows the error on the field or at the top of the page. For checks like these, it is the best choice:
- A field is required when another field has a certain value.
- A number is within a range.
- A text value matches a pattern.
- A value is consistent with a parent record, reached through a cross-object reference.
If the requirement fits in a formula, use a rule. Everything below covers requirements that don't fit.
Where a formula runs out
A validation rule has these constraints:
- It sees one record. The formula can read the record and its parents (through lookups and master-detail relationships, up to 10 relationship hops). It cannot query siblings or unrelated objects. "No other open Opportunity on this Account may have the same Name" cannot be written as a formula.
- It cannot query children. The only way to use child data is a roll-up summary field on a master-detail parent, which the formula can then reference. Lookup relationships do not support roll-up summaries.
- It cannot change data. A rule only allows or blocks the save. It cannot set a default, clean up a value, or create a related record.
- It does not run on delete. You cannot block a deletion with a validation rule.
- It cannot call external systems. There are no callouts and no lookups into other services.
- It has size limits. A formula has a maximum length and compiled size. Long chains of nested
IFandREGEXcalls hit these limits, and they are also hard to read. - Its error options are fixed. You get one message, shown on one field or at the top of the page. You cannot build a message from the results of a query, or show different text to different users beyond what the formula can express.
When a requirement hits one of these limits, the next question is which tool replaces the rule.
Choosing between a rule, a flow, and Apex
| Requirement | Validation rule | Record-triggered flow | Apex trigger |
|---|---|---|---|
| Compare fields on the same record | Best fit | Works, but heavier | Works, but heavier |
| Check a parent's field | Good | Good | Good |
| Query unrelated or sibling records | No | Yes (Get Records) | Yes (SOQL) |
| Block a delete | No | Yes, with a before-delete flow and a custom error | Yes, with `addError()` |
| Modify the record, then validate | No | Yes, in a before-save flow | Yes, in a before trigger |
| Complex logic, loops over many records | No | Possible, gets hard to maintain | Best fit |
| Maintainable by admins without code | Yes | Yes | No |
| Needs deployment tests | No | Flow tests are optional | Yes, 75% coverage required in production |
Two points in the table need explaining:
- Flows. A record-triggered flow can stop a save with a Custom Error element. This only works in flows that run before the save. A flow that has already committed the record cannot undo it. Use a flow when an admin must own the logic and the check needs a query, a branch, or a field update first.
- Apex. Choose a trigger when the logic needs loops, bulk-safe queries across many records, callouts handled through asynchronous work, or shared code that other automation reuses. Apex carries the cost of tests, deployments, and developer time.
A requirement a rule cannot meet
The business asks: "Do not allow an Account to be deleted while it has open Opportunities." A validation rule never fires on delete, so it cannot enforce this. A before-delete trigger can:
trigger AccountDeleteGuard on Account (before delete) {
Set<Id> accountsWithOpenOpps = new Set<Id>();
for (AggregateResult ar : [
SELECT AccountId acctId
FROM Opportunity
WHERE AccountId IN :Trigger.oldMap.keySet()
AND IsClosed = false
GROUP BY AccountId
]) {
accountsWithOpenOpps.add((Id) ar.get('acctId'));
}
for (Account acc : Trigger.old) {
if (accountsWithOpenOpps.contains(acc.Id)) {
acc.addError('This account has open opportunities. Close or reassign them before deleting the account.');
}
}
}The trigger runs one query for the whole batch and then adds an error to each offending record. That pattern keeps it safe when a user deletes hundreds of Accounts at once. addError() blocks only the records it is called on, and the user sees the message in the same way as a validation rule message.
Where each tool sits in the save
The tools run at different points in the order of execution, and that affects what each one sees.
Because before-save flows and before triggers run ahead of validation rules, the rule sees the values they set. A before-save flow that fills a default Region__c means a rule that requires Region__c passes. If you move a check from a rule into a before trigger, its error now fires before the remaining rules do. A user may fix one error and then hit another one on the next save. Rules also all run together, so a user sees all rule errors at once. Keep that in mind before splitting one requirement across tools.
Failure modes to watch for
- Duplicated logic. A rule says Amount must be positive, and a trigger enforces the same thing with different wording. When the requirement changes, one of them gets missed. Pick one home for each requirement.
- Bypass gaps. A rule can use a custom permission for bypass. Flows and Apex do not read that setting on their own. If data loads need an exemption, the flow or trigger must check the permission too, for example with
FeatureManagement.checkPermission('Bypass_Validation_Rules')in Apex. - Hidden ordering effects. An after-save flow cannot prevent a save the way a before-save flow can. Putting a "validation" step in an after-save flow can leave related records half-updated.
- Bulk limits. A flow that runs a Get Records element inside a loop can hit governor limits during a data load. Query once outside the loop, then loop over the results.
- Unclear ownership. A requirement that spans a rule, a flow, and a trigger is hard to debug. Document where each requirement lives.
A short decision process
- Can the check be written using only fields on this record and its parents? If yes, use a validation rule.
- If not, does the check need a query, a branch, or a prior field update, and should an admin maintain it? Use a before-save record-triggered flow with a Custom Error.
- If the logic involves delete events, heavy bulk processing, callouts, or shared code, use an Apex trigger with
addError(). - Whatever you pick, add a bypass if data loads or integrations need an exemption, and write an Apex test that proves the block.
Exercise
A sales manager wants to stop users from saving an Opportunity if the same Account already has another open Opportunity with the same Name. Which tool should you pick, and why can't a validation rule do it?
Show answer
Use an Apex before-insert and before-update trigger, or a before-save record-triggered flow that uses Get Records and a Custom Error. A validation rule can read only the current record and its parents, so it cannot query other Opportunities on the same Account. The trigger or flow can query for open Opportunities with the same Account and Name, excluding the current record on update, and block the save when it finds one.
Exercise
Your team uses a bypass custom permission for a nightly integration. You replace a validation rule with a before trigger. What must you add so the integration is still exempt?
Show answer
Add a check for the custom permission in the trigger, for example FeatureManagement.checkPermission('Bypass_Validation_Rules'), and skip the validation logic when it returns true. A trigger does not read the $Permission clause that the old rule used.