PracticeVideosBlogFlashcards

5.3 Validation Rules & Error Handling Strategies

Key Takeaways

  • A validation rule halts the record save transaction and displays a custom error message when its formula expression evaluates to TRUE (representing the invalid condition).

  • The ISCHANGED() and PRIORVALUE() functions compare proposed updates against existing database values during update operations, while ISNEW() identifies newly inserted records.

  • Custom validation rules execute after system validations and Before-Save Record-Triggered Flows, but prior to After-Save Record-Triggered Flows, duplicate rules, and workflow rules in the platform save cycle.

  • Validation errors directed to a field not visible on the user's page layout or hidden by field-level security automatically reroute and display at the Top of Page.

  • Enterprise validation rules should incorporate bypass mechanisms leveraging Custom Permissions ($Permission) or Hierarchical Custom Settings ($Setup) to facilitate frictionless data migrations and automated integration transactions.

Last updated: October 2026

Validation Rules & Error Handling Strategies

Data integrity is the bedrock of any successful enterprise Salesforce implementation. Without rigorous data quality guardrails, downstream automations fail, business analytics produce misleading insights, and sales and service teams lose confidence in the CRM platform. Validation rules are Salesforce's primary declarative mechanism for enforcing business constraints and preventing invalid, inconsistent, or incomplete data from entering the database.


Core Mechanics & Architectural Philosophy

A Validation Rule consists of a formula expression and a user-facing error message. The most fundamental concept to master for the Platform App Builder exam is the boolean evaluation rule:

Formula Evaluates to TRUE   --->  Data is INVALID  --->  Save Aborted & Error Displayed
Formula Evaluates to FALSE  --->  Data is VALID    --->  Save Permitted to Proceed

Unlike traditional programming assertions where a condition must evaluate to true to continue, in Salesforce a validation rule formula defines the invalid condition. When the formula evaluates to TRUE, the platform halts the save cycle, rolls back pending in-memory database modifications, and displays the designated error message to the user or API client.

Universal Platform Scope

Validation rules enforce data integrity across every data entry and manipulation vector in the Salesforce ecosystem:

  • Standard Lightning record page edits and full edit modals.
  • Inline editing in list views and multi-line edit grids.
  • Salesforce Mobile App interactions.
  • Quick Actions and Screen Flows.
  • Automated background updates via Record-Triggered Flows and Apex triggers.
  • External data operations via SOAP, REST, and Bulk APIs (including Data Loader, MuleSoft, and third-party ETL tools).
  • Public data intake endpoints, including Web-to-Lead and Web-to-Case.

Note

Web-to-Lead and Web-to-Case Behavior: When a web submission violates an active validation rule, the lead or case is rejected from creation. Salesforce sends an automated notification email containing the error details and submitted form parameters to the default lead or case creator specified in Setup.


Essential Validation Formula Functions

Building sophisticated validation rules requires mastery of five specialized functions that inspect record state, historical field values, and string formatting patterns:

1. ISNEW()

Returns TRUE if the record is currently being inserted into the database as a new record; returns FALSE during record update transactions. ISNEW() is essential when rules must apply exclusively during record creation, such as mandating specific onboarding fields that should not block edits on historical legacy records:

AND(
  ISNEW(),
  ISBLANK(Initial_Security_Deposit__c)
)

2. ISCHANGED(field)

Compares the proposed new value of a field against its existing value currently stored in the database. Returns TRUE if the value has changed; returns FALSE if unchanged. During record creation (ISNEW()), ISCHANGED() evaluates to FALSE ; use OR(ISNEW(), ISCHANGED(Field__c)) when the rule must also apply on creation.

3. PRIORVALUE(field)

Returns the value of a field immediately prior to the current save transaction. On a newly created record, PRIORVALUE() returns the current value; use NOT(ISNEW()) if the rule must apply only to existing records. During updates, PRIORVALUE() and is the key function for enforcing state transition rules, preventing backwards stage progression, and locking fields after milestones are reached:

/* Prevent moving Opportunity Stage backward once reached Closed Won */
AND(
  ISPICKVAL(PRIORVALUE(StageName), "Closed Won"),
  NOT(ISPICKVAL(StageName, "Closed Won"))
)

4. REGEX(text, regex_pattern)

Matches a text field against a regular expression pattern and returns TRUE if the text conforms to the regex. In validation rules, because the formula must return TRUE on error, app builders wrap REGEX() inside NOT() to fire an error whenever data fails the formatting rule. In Salesforce formulas, backslashes must be escaped with double backslashes (e.g., \d):

/* Enforce US 5-digit or 9-digit Zip Code format */
AND(
  NOT(ISBLANK(PostalCode)),
  NOT(REGEX(PostalCode, "\\d{5}(-\\d{4})?"))
)

5. VLOOKUP(field_to_return, field_on_lookup_object, lookup_value)

A specialized function with three strict platform limitations:

  1. Only available in Validation Rules (cannot be used in formula fields or Flows).
  2. Only available on Custom Objects.
  3. Can only look up against the standard Name field of another custom object.

VLOOKUP() searches a target custom object table where field_on_lookup_object (the Name field) matches lookup_value and returns field_to_return. A classic exam scenario uses VLOOKUP() to validate that a custom state postal code matches a tax rate record in a State_Tax__c lookup table.


Error Message UX and UI Placement Mechanics

When a validation rule formula evaluates to TRUE, Salesforce prevents the save and presents the configured error message. App builders must select one of two UI display locations:

Error LocationVisual RenderingOptimal Business Use CasesPlatform Fallback Behavior
Top of PageDisplayed in an error alert banner at the top of the record page or modal.Multi-field cross-validation rules (e.g., "If Delivery Type is Express, Shipping Notes and Priority Level are required").Standard primary rendering location.
FieldHighlights the specific input field in red with the error message rendered directly underneath.Single-field validation rules (e.g., "Tax ID must follow the 999-99-9999 format").Graceful Reroute: If the target field is not on the user's page layout or hidden by FLS, the error automatically displays at the Top of Page.

Important

The Missing Field Fallback Gate: A frequent exam scenario asks what occurs when a validation rule is configured to display next to a specific field, but that field is not added to the user's assigned Page Layout (or is hidden via Field-Level Security). Salesforce does not swallow the error or crash the transaction. Instead, the platform automatically redirects and renders the error message at the Top of Page, preserving data integrity while notifying the user.


Validation Rules in the Platform Order of Execution

Use the relative order to reason about a save. The full sequence includes conditional stages and repeat-save behavior; this is the essential App Builder path:

  1. Salesforce loads the record and submitted values and performs initial system checks.
  2. Before-save record-triggered flows modify the in-memory triggering record.
  3. Before Apex triggers run, followed by system checks and custom validation rules.
  4. Duplicate rules run. The record is saved and receives an ID on insert, but the transaction is still uncommitted.
  5. After Apex triggers, assignment rules, auto-response rules, and legacy workflow processing run.
  6. Escalation rules, legacy processes and their invoked flows, and immediate after-save record-triggered flows execute, followed by applicable entitlement processing.
  7. Roll-up calculations and related parent save procedures run. Salesforce then commits the transaction.
  8. Post-commit processing includes queued asynchronous Flow paths and email delivery.

A before-save flow can populate a value before a custom validation rule evaluates it, but do not depend on it to rescue an input rejected by an earlier system-required-field check. Immediate after-save flows are not post-commit jobs: a later error can still roll back their work.

Legacy workflow field updates have special repeat-save behavior. They rerun before/after Apex triggers without rerunning custom validation rules in that workflow update cycle. Approval field updates also do not automatically pass through custom validation rules. Distinguish these from ordinary Flow Update Records operations, which use normal record-save behavior. Test the actual combination of automation in a sandbox.


Enterprise Bypass Architectures for Migrations and Integrations

During large-scale data migrations (e.g., importing 300,000 legacy records via Data Loader) or high-frequency automated integrations (e.g., an ERP syncing invoices via an API integration user), historical data frequently violates newly implemented validation rules.

The Anti-Pattern: Manual Deactivation

A naive administrator might navigate into Setup, manually uncheck "Active" on 25 validation rules, run the migration, and reactivate the rules afterward. This approach introduces extreme organizational risk:

  • Standard business users interacting with Salesforce during the migration window can enter dirty, invalid data without restriction.
  • Administrators frequently forget to reactivate all rules or fail to reactivate them with original configurations.
  • Automated unit tests and continuous integration deployments can fail during the deactivated window.

Solution 1: Custom Permissions ($Permission)

The modern enterprise standard leverages Custom Permissions incorporated directly into the validation rule formula expression. Custom Permissions provide granular, metadata-driven bypass capability that can be assigned directly to specific integration users or migration administrators via Permission Sets.

Step-by-Step Implementation:

  1. Navigate to Setup and create a Custom Permission named Bypass_Validation_Rules.
  2. Create a Permission Set named Data_Migration_Exemptions and enable the Bypass_Validation_Rules custom permission.
  3. Assign the Permission Set to the integration user or migration admin.
  4. Update the validation rule formula to check $Permission.Bypass_Validation_Rules:
AND(
  NOT($Permission.Bypass_Validation_Rules),
  ISBLANK(Mandatory_Tax_ID__c)
)

When standard users edit a record, $Permission.Bypass_Validation_Rules evaluates to FALSE, making NOT(...) evaluate to TRUE, so the validation rule enforces normally. When the migration user saves a record, $Permission.Bypass_Validation_Rules evaluates to TRUE, making NOT(...) evaluate to FALSE, which immediately evaluates the entire AND() statement to FALSE, allowing the record to save seamlessly.

Solution 2: Hierarchical Custom Settings ($Setup)

Another widely deployed architecture utilizes a Hierarchical Custom Setting (e.g., Automation_Bypass__c) with a checkbox field Bypass_Validation__c. Hierarchical custom settings allow default configurations at the Organization level (set to FALSE), with granular overrides at the Profile or User level (set to TRUE for the Integration Profile):

AND(
  NOT($Setup.Automation_Bypass__c.Bypass_Validation__c),
  CloseDate < TODAY()
)

Validation Rule Function Matrix

FunctionReturn TypeContext AvailabilityCore Exam Use Case
ISNEW()BooleanInsert and update (true only on insert)Enforces required fields exclusively during initial record creation.
ISCHANGED(field)BooleanUpdate onlyTriggers validation only when a specific field value has been modified.
PRIORVALUE(field)Field TypeInsert/update; current value on insertCompares proposed value against database value; prevents backwards stage changes.
REGEX(text, pattern)BooleanInsert & UpdateEnforces alphanumeric formatting (Tax IDs, postal codes, phone numbers).
VLOOKUP(return, field, val)Matches returnValidation Rules on Custom Objects onlyValidates against the Name field of a custom object lookup table.
$Permission.NameBooleanInsert & UpdateGlobal variable enabling frictionless administrative and integration bypass.
$Setup.Setting.FieldMatches fieldInsert & UpdateHierarchical custom setting access for user- and profile-level bypass logic.

Official Source Check

Checked October 19, 2026: Official save order.

Loading diagram...
Salesforce Order of Execution: Validation Rules and Bypass Gates
Test Your Knowledge

Universal Containers requires that once an Opportunity reaches the 'Closed Won' stage, users cannot decrease the Opportunity Amount or change the Close Date to an earlier date. Which validation rule formula correctly enforces this business requirement?

A

AND( ISPICKVAL(PRIORVALUE(StageName), "Closed Won"), OR( Amount < PRIORVALUE(Amount), CloseDate < PRIORVALUE(CloseDate) ) )

B

AND( ISPICKVAL(StageName, "Closed Won"), OR( ISCHANGED(Amount), ISCHANGED(CloseDate) ) )

C

IF(AND(ISPICKVAL(PRIORVALUE(StageName), "Closed Won"), OR(ISCHANGED(Amount), ISCHANGED(CloseDate))), OR(Amount > PRIORVALUE(Amount), CloseDate > PRIORVALUE(CloseDate)), FALSE)

D

OR( AND(ISPICKVAL(StageName, "Closed Won"), Amount < PRIORVALUE(Amount)), CloseDate < TODAY() )

Test Your Knowledge

An enterprise architect is preparing an org for a large-scale data migration of 250,000 legacy Account records. Many legacy records lack the newly mandatory Tax_ID__c field enforced by a production validation rule. The migration must complete without disabling rules globally in Setup or allowing standard business users to create invalid records. What is the recommended best practice?

A

Request a temporary 48-hour global suspension of all validation rules from Salesforce Support

B

Change the validation rule error location to Top of Page and execute the migration during non-business hours

C

Delete the validation rule from production, run the Bulk API load, and then redeploy the rule with an inbound Change Set, which automatically revalidates all 250,000 migrated Account records against the reactivated rule inside a single transaction

D

Incorporate a Custom Permission check ($Permission.Bypass_Validation_Rules) into the validation rule formula and assign the permission to the migration user via a Permission Set

Test Your Knowledge

An app builder creates a validation rule that verifies a custom Employee_Tax_ID__c text field follows the format of three digits, a hyphen, two digits, a hyphen, and four digits (999-99-9999). Which formula expression should the app builder use to trigger the validation error if the format is invalid?

A

NOT(REGEX(Employee_Tax_ID__c, "\\d{3}-\\d{2}-\\d{4}"))

B

REGEX(Employee_Tax_ID__c, "[0-9]{3}-[0-9]{2}-[0-9]{4}")

C

AND(LEN(Employee_Tax_ID__c) == 11, VLOOKUP(Employee_Tax_ID__c, Tax_Table__c.Name, Employee_Tax_ID__c))

D

NOT(CONTAINS(Employee_Tax_ID__c, "###-##-####"))

Sections you finish are checked off in the contents.