Skip to content

Complex Validation Rule using Salesforce Record Trigger Flows Instead of using Apex code

This article walks you through creating a validation rule using a record trigger flow instead of using apex code for complex business requirements. Sometimes we have requirements that can not be accomplished using standard validation rules. So you can use this approach instead of developing before insert apex trigger.

Some of the limitations in the standard validation rules are mentioned below.

  • You can not reference PRIORVALUE function on a field from lookup values such as Parent.RecordType.DeveloperName.
  • You can not reference the related records data in validation rules, such as related activity history.

Now let’s say we have a business requirement that before an opportunity is marked as closed won, the opportunity must have at least one contact role and we are going to accomplish this via record trigger flow + validation rule without a single line of coding.

Demo video

STEP 1:

Since our rule should run when an opportunity is marked as closed won. So first create a checkbox field on the opportunity object and set the default value as unchecked. Make sure to not add the field to the page layouts.

Custom Checkbox field on the opportunity object. This should be hidden from the layouts.

STEP 2

Created a record trigger flow that should configure to run when an opportunity stage is updated to closed won. See attached screenshot.

Record trigger flow setup, when the opportunity is updated to closed won

Then add a Get Records element to the flow and get the related opportunity contact roles as shown in the following screenshot.

Get related opportunity contact roles of the opportunity

Now using the decision element check, if no opportunity contact roles are found then update the checkbox field (created in step 1) to true.

Decision element to check if opportunity contact roles are found or not.
Update the checkbox field on the record, if no opportunity contact roles are found.
The final look of the record trigger flow.

STEP 3

Create a validation rule on the opportunity object, that should run when the checkbox field is checked and throw an error message. The validation rule formula is copied below.

AND(
At_Least_one_OCR_Validation__c = TRUE,
ISCHANGED(At_Least_one_OCR_Validation__c)
)
Validation rule

STEP 4

Once you have completed all the above steps, make sure to activate the record trigger flow created in step 2 and activate the validation rule created in step 3.

The validation rule will automatically trigger whenever the opportunity stage is updated. Because if you look at the Salesforce Order of Execution, when the before trigger flow runs and update the checkbox field, the custom validation rules are triggered again to verify all the required fields have a non-null value.