Formula Fields and Validation Rules
Formula Fields and Validation Rules are two powerful declarative features in Salesforce that allow developers and administrators to implement business logic without writing Apex code. **Formula Fields** are read-only fields that automatically calculate their values based on expressions you define.… Formula Fields and Validation Rules are two powerful declarative features in Salesforce that allow developers and administrators to implement business logic without writing Apex code. **Formula Fields** are read-only fields that automatically calculate their values based on expressions you define. They can reference other fields, use operators, and leverage built-in functions. Formula fields are evaluated in real-time whenever a record is viewed. Key characteristics include: - They support various return types: Text, Number, Date, DateTime, Currency, Percent, and Checkbox. - They can reference fields from related objects using cross-object formulas (up to 10 relationships). - They have a compile size limit of 5,000 characters and cannot exceed the formula field limit per object. - Common functions include IF(), CASE(), ISBLANK(), TEXT(), TODAY(), NOW(), and VLOOKUP(). - They are calculated dynamically and are not stored in the database (except in reporting indexes). - Example: A formula field calculating total price as Quantity__c * Unit_Price__c. **Validation Rules** enforce data quality by preventing users from saving records that don't meet specified criteria. They evaluate an expression that returns TRUE or FALSE — when TRUE, the record is rejected and an error message is displayed. Key characteristics include: - They fire when a record is created or updated via any method (UI, API, Apex, etc.). - Error messages can be displayed at the top of the page or next to a specific field. - They can reference fields on the current object and related parent objects. - They support the same functions available in formula fields. - They execute after before-triggers in the order of execution. - Example: A rule ensuring a Close Date is not in the past: CloseDate < TODAY(). Both features are essential for the Platform Developer I exam. Understanding their capabilities, limitations, and how they fit into the Salesforce order of execution is critical. They represent best-practice declarative solutions that should be used before resorting to programmatic approaches like Apex triggers.
Formula Fields and Validation Rules – Salesforce Platform Developer 1 Exam Guide
Introduction
Formula Fields and Validation Rules are two of the most fundamental declarative tools on the Salesforce platform. They appear frequently on the Salesforce Platform Developer 1 (PD1) exam because they test your understanding of declarative logic, data integrity, cross-object relationships, and the boundary between clicks and code. Mastering these topics is essential not only for passing the exam but also for building efficient, maintainable solutions in real-world projects.
Why Are Formula Fields and Validation Rules Important?
1. Declarative-First Approach: Salesforce strongly encourages using declarative (point-and-click) solutions before writing code. Formula fields and validation rules let you implement complex business logic without Apex, reducing development time, maintenance overhead, and the risk of governor limit issues.
2. Data Integrity: Validation rules act as gatekeepers, ensuring that data entered into the system meets specific criteria before a record is saved. This is critical for downstream reporting, integrations, and process automation.
3. Real-Time Calculations: Formula fields calculate values on the fly, providing users with derived information (e.g., margins, age calculations, concatenated text) without storing redundant data.
4. Cross-Object Access: Formula fields can reference fields on related parent objects (up to 10 relationships deep on some object types), enabling powerful data surfacing without code.
5. Exam Relevance: The PD1 exam blueprint allocates significant weight to the "Developer Fundamentals" and "Data Modeling and Management" sections, both of which heavily feature formula fields and validation rules.
What Are Formula Fields?
A formula field is a read-only field whose value is calculated dynamically based on an expression you define. The value is not stored in the database; it is computed each time the record is viewed or queried.
Key Characteristics:
- Formula fields are read-only; users and code cannot directly write to them.
- They can return various data types: Text, Number, Currency, Date, Date/Time, Checkbox (Boolean), and Percent.
- They can reference fields on the same object or span relationships to parent objects using dot notation (e.g., Account.Industry on a Contact formula).
- They can use functions such as IF(), CASE(), ISBLANK(), ISNULL(), TEXT(), VALUE(), TODAY(), NOW(), DATEVALUE(), BLANKVALUE(), PRIORVALUE() (only in certain contexts), REGEX(), and many more.
- Formula fields count toward a per-object compiled character limit (currently 5,000 compiled characters per field, and a total object limit).
- They are evaluated at read time, not at save time (unlike workflow field updates).
Common Use Cases:
- Calculating the number of days since an opportunity was created: TODAY() - DATEVALUE(CreatedDate)
- Displaying a full name: FirstName & " " & LastName
- Returning a conditional value: IF(Amount > 100000, "Large Deal", "Standard Deal")
- Cross-object references: Account.Owner.Email on a Contact
- Image formulas using the IMAGE() function to display icons based on conditions
Important Limitations:
- Cannot reference child records (no aggregation like roll-up; use Roll-Up Summary fields or Apex for that).
- Cannot be used in certain places where writable fields are required (e.g., as the target of a workflow field update).
- Performance considerations when formulas span many relationships or are deeply nested.
- Cross-object formulas on standard objects can span up to 10 relationships; on custom objects this is also subject to limits.
What Are Validation Rules?
A validation rule is a business logic rule that runs before a record is saved. If the rule's formula expression evaluates to TRUE, the save is blocked and an error message is displayed to the user.
Key Characteristics:
- The error condition formula must evaluate to TRUE for the error to fire (this is a very common exam trick — remember: TRUE = error).
- Validation rules fire on record insert and update (and upsert) operations, including those triggered by Apex, API, and UI actions.
- You can display the error at the top of the page or next to a specific field.
- Validation rules have access to the same formula functions available to formula fields, plus some additional context functions like ISNEW(), ISCHANGED(), and PRIORVALUE().
- They fire after before-triggers (system validation, then custom validation rules, then after-triggers, then assignment rules, etc.).
- They respect field-level security and profile-based access but evaluate regardless of the source of the DML operation (UI, Apex, API).
Common Use Cases:
- Requiring a field when a certain condition is met: ISPICKVAL(Status, "Closed") && ISBLANK(ClosedDate)
- Preventing changes to a record after it reaches a certain stage: ISCHANGED(Amount) && ISPICKVAL(StageName, "Closed Won")
- Ensuring a number is within a valid range: Discount__c > 0.40 (error if discount exceeds 40%)
- Enforcing data format with REGEX: NOT(REGEX(Phone, "\\d{10}"))
Important Limitations:
- Validation rules do NOT fire during lead conversion (unless specific settings are enabled).
- They do NOT fire for records that are being deleted.
- They can be bypassed by system-level operations in certain edge cases (e.g., mass transfer, some managed package operations).
- When a validation rule blocks a save in Apex, it throws a DmlException that should be caught and handled.
How Do They Work Together in the Order of Execution?
Understanding the Salesforce Order of Execution is crucial for the exam:
1. System validations (required fields, field formats) run first.
2. Before triggers execute.
3. System validations run again (after before-trigger changes), and then custom validation rules execute.
4. Record is saved to the database (but not committed).
5. After triggers execute.
6. Assignment rules, auto-response rules, workflow rules, and then processes/flows execute.
7. The transaction is committed.
This means:
- Validation rules see values that have been modified by before triggers.
- If a validation rule fails, after triggers, workflows, and processes do NOT execute.
- Formula fields are not "saved" — they compute at read time — so they are always current when viewed.
Key Functions to Know for the Exam
Common Formula Functions:
- IF(condition, true_value, false_value) — conditional logic
- CASE(expression, val1, result1, val2, result2, ..., else_result) — multi-branch logic
- ISBLANK(expression) — checks if a field is blank (preferred over ISNULL for text fields)
- ISNULL(expression) — checks for null; use ISBLANK instead for text fields
- BLANKVALUE(field, substitute) — returns substitute if field is blank
- NULLVALUE(field, substitute) — returns substitute if field is null
- TEXT(picklist_field) — converts picklist to text for use in formulas
- ISPICKVAL(picklist_field, "value") — compares picklist value (use this, NOT == for picklists)
- TODAY() — returns the current date (Date type)
- NOW() — returns the current date/time (DateTime type)
- DATEVALUE(datetime_field) — extracts the date portion from a DateTime
- REGEX(text, pattern) — tests a text field against a regular expression pattern
- HYPERLINK(url, label) — creates a clickable link
- IMAGE(url, alt_text) — displays an image
Validation-Specific Functions:
- ISNEW() — returns TRUE if the record is being created (insert, not update)
- ISCHANGED(field) — returns TRUE if the field value has changed (only on update)
- PRIORVALUE(field) — returns the previous value of a field (only on update)
Important Notes:
- ISNEW(), ISCHANGED(), and PRIORVALUE() are available in validation rules but NOT in formula fields (this is a frequent exam question!).
- ISPICKVAL() must be used for picklist comparisons in formulas, not the == operator with TEXT().
- ISBLANK() is generally preferred over ISNULL() — Salesforce recommends ISBLANK() as it handles text fields correctly.
Exam Tips: Answering Questions on Formula Fields and Validation Rules
1. TRUE Means Error: The single most important thing to remember about validation rules is that when the formula evaluates to TRUE, the record is rejected. Many exam questions try to trick you by reversing the logic. Read the requirement carefully and determine which condition should block the save — that condition must evaluate to TRUE.
2. Formula Fields Are Read-Only: If an exam question asks you to "automatically populate" or "set" a field value, a formula field might be the answer only if no one needs to edit that value. If the business needs to override the value, you need a different approach (e.g., a before trigger, workflow field update, or flow).
3. Know Which Functions Are Available Where: ISCHANGED(), ISNEW(), and PRIORVALUE() work in validation rules and Apex triggers but are NOT available in formula fields. If an exam question references one of these functions in a formula field context, it is likely the wrong answer.
4. Picklist Handling: Always use ISPICKVAL() to compare picklist values in formulas. Using == with a picklist field directly is a common incorrect answer choice. TEXT() can convert a picklist to text, but ISPICKVAL() is the standard approach for comparisons.
5. Cross-Object Formula Fields: Remember that formula fields can only traverse upward (to parent records via lookup/master-detail relationships). They cannot aggregate or reference child records. If the question asks about summarizing child data, think Roll-Up Summary fields or Apex.
6. Order of Execution Matters: Validation rules fire after before triggers. This means before-trigger logic can modify field values before validation rules evaluate them. If an exam question describes a scenario where a before trigger sets a value and then asks whether a validation rule will catch it, the answer is yes — the validation rule sees the modified value.
7. ISBLANK() vs. ISNULL(): Salesforce recommends ISBLANK() over ISNULL(). ISNULL() does not work correctly with text fields (it does not treat empty strings as null). On the exam, prefer answers using ISBLANK().
8. Compound Conditions: Exam questions often combine AND (&&) and OR (||) logic. Break down the requirement step by step. For example: "Prevent saving if Status is Closed AND Amount is blank" translates to: ISPICKVAL(Status, "Closed") && ISBLANK(Amount).
9. Date Arithmetic: Date - Date returns a Number (days). Date + Number returns a Date. DateTime fields require DATEVALUE() to extract the date portion. TODAY() returns Date; NOW() returns DateTime. Mixing types without conversion is a common exam trap.
10. Compile Size Limits: Be aware that formula fields have a compiled size limit (5,000 characters per formula). If the exam asks about limitations of formula fields, this is a valid constraint.
11. Lead Conversion: By default, validation rules do NOT fire during lead conversion. This is a niche but testable fact.
12. Error Message Placement: Validation rule errors can appear at the top of the page or adjacent to a specific field. If the field referenced in the error location is not on the page layout, the error appears at the top.
13. Declarative vs. Programmatic: If the exam describes a requirement that can be solved with a validation rule or formula field, the declarative approach is almost always the preferred answer over Apex — unless there is a specific reason code is required (e.g., complex cross-object updates, callouts, etc.).
14. Watch for Null Handling: Numeric formula fields treat blank/null values as zero by default (if "Treat blank fields as zeros" is selected). Text formula fields treat blanks as empty strings. This default behavior can affect your formula logic and is occasionally tested.
15. Practice Reading Formulas: The exam may present a formula and ask what it does or what error it contains. Practice reading nested IF(), CASE(), and compound logical expressions so you can quickly parse them under time pressure.
Summary
Formula fields and validation rules are essential declarative tools every Salesforce developer must master. Formula fields provide dynamic, read-only calculated values that can span object relationships, while validation rules enforce data integrity by blocking saves when business conditions are violated. For the Platform Developer 1 exam, focus on understanding the TRUE = error paradigm for validation rules, the read-only nature of formula fields, proper function usage (especially ISPICKVAL, ISBLANK, ISCHANGED, ISNEW), the order of execution, and the distinction between declarative and programmatic solutions. With a solid understanding of these concepts, you will be well-prepared to tackle formula and validation rule questions with confidence.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!