Chuyển đến nội dung

Bài 13 · Objects, Fields and Data Model

Validation Rules: Enforcing Data Quality

Learn to write Salesforce validation rules that block bad data: error condition formulas, ISNEW, ISCHANGED, PRIORVALUE, REGEX, error messages and bypass patterns.

A validation rule checks the data when a user saves a record. If the rule's formula returns TRUE, the save is blocked and an error message appears. This single idea is one of the strongest tools admins have against bad data: required fields that are conditional, consistent dates, valid formats, and process gates.

The key idea: the formula describes the error

Many beginners write the rule backwards. The formula must be TRUE when the data is wrong. Compare:

  • Goal: "Close Date is required when the stage is Closed Won."
  • Formula: AND(ISPICKVAL(StageName, "Closed Won"), ISBLANK(CloseDate))

When both parts are true (closed won with a blank date), the rule fires and blocks the save. When the rule returns FALSE, the save continues.

Creating a validation rule

Setup > Object Manager > the object > Validation Rules > New.

  1. Rule Name: letters, numbers and underscores, for example Require_Amount_After_Proposal.
  2. Active: tick it to turn it on (untick to deactivate temporarily).
  3. Description: explain the business reason.
  4. Error Condition Formula: write the formula. Use Check Syntax.
  5. Error Message: what the user reads; make it specific and actionable.
  6. Error Location: Top of Page or beside a specific Field.
  7. Save, then test.

An object can have many validation rules; they all run. Rules run on create and update, whether the save comes from the UI, an import, a flow or the API.

Useful functions

  • ISBLANK(field): true if empty. Use ISBLANK for most fields; for text, it also treats a blank string as blank.
  • ISPICKVAL(field, "value"): picklist test.
  • AND(), OR(), NOT().
  • ISNEW(): true when the record is being created.
  • ISCHANGED(field): true if the value changed in this save.
  • PRIORVALUE(field): the value before the edit.
  • LEN(text), CONTAINS(text, substring), BEGINS(text, prefix).
  • REGEX(text, "pattern"): whether the entire text matches a regular expression.
  • TODAY(), date arithmetic.
  • $User.ProfileId, $Profile.Name, $Permission.Name (custom permission) and $UserRole.Name for exemptions.

Examples

Phone must be 10 digits:

Text
AND(NOT(ISBLANK(Phone)), NOT(REGEX(Phone, "[0-9]{10}")))

Close Date cannot be in the past on a new opportunity:

Text
AND(ISNEW(), CloseDate < TODAY())

Amount cannot be edited after the deal is Closed Won, except by a custom permission:

Text
AND(
  ISPICKVAL(PRIORVALUE(StageName), "Closed Won"),
  ISCHANGED(Amount),
  NOT($Permission.Edit_Closed_Deals)
)

End date must be after start date:

Text
AND(NOT(ISBLANK(End_Date__c)), End_Date__c < Start_Date__c)

Require a reason when a case is closed:

Text
AND(ISPICKVAL(Status, "Closed"), ISBLANK(Resolution__c))
Python Stand-in: run validation rules on a record

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Order of execution and where validation sits

When a record is saved, Salesforce runs many steps in a fixed order. In simplified form: system validation (required fields, field formats), before-save flows and before triggers, then custom validation rules, then the record is saved to the database (not yet committed), after-save triggers and flows, assignment and auto-response rules, roll-ups, and finally the commit. The practical lesson: a before-save flow can fill in a value that a validation rule then checks, and validation rules protect against values from any source.

Designing good rules

  • One rule, one purpose. Easier to name, debug and switch off.
  • Name them clearly: Opp_Amount_Required_After_Proposal.
  • Write a clear error message: "Enter an Amount before moving the opportunity to Proposal/Price Quote." Not "Invalid data."
  • Put the error on the field when it concerns one field.
  • Avoid hardcoding IDs and names: use custom permissions, custom metadata or custom labels instead of $Profile.Name = "Sales".
  • Add a bypass for data migrations and integrations. A common pattern is a hierarchy custom setting or a custom permission that, when granted, turns off the rules for that user. Example: AND(NOT($Setup.Bypass__c.Skip_Validation__c), ...).
  • Document the rule's purpose in the Description box.
  • Test with each save path: the UI, a data import, a flow, an integration. A rule that blocks the integration user is a classic outage.
Python Stand-in: a bypass switch

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Debugging

If a rule does not behave as you expect: check Active; look at the exact error message on screen; use Check Syntax; remember that a formula referencing a field the user cannot see still works (rules run in system mode); and use a debug log (Setup > Debug Logs) to see which rule fired. You can also use the Formula Editor Insert Field button to avoid typos in API names.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. When does a validation rule block the save?

    The error condition formula describes bad data; TRUE means error and blocks the save.
  2. 2. Which function tells you the value of a field before the user edited it?

    PRIORVALUE returns the previous value; ISCHANGED tells whether it changed.
  3. 3. Which rule makes Resolution required once a case is closed?

    The rule must be TRUE when the status is Closed and the resolution is blank. Option 3 inverts the condition and would block good data.
  4. 4. Why add a bypass for validation rules?

    Bypass switches (custom permissions or custom settings) let controlled processes skip rules.

Summary

  • A validation rule fires (and blocks the save) when its formula is TRUE, so write the condition for the bad data.
  • Use ISNEW, ISCHANGED, PRIORVALUE, REGEX and custom permissions for precise rules.
  • Write specific error messages, place errors on the field, and test every save path.
  • Add a documented bypass for migrations and integrations.

Next: Page Layouts, Record Types and Lightning Pages

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.