# Formulas, Validation Rules & Roll-ups

> Formula fields, cross-object formulas, validation rule recipes with ISCHANGED/PRIORVALUE/REGEX and roll-up summaries.

**Track:** admin · **Category:** Data Quality · **Topics:** Formulas, Validation rules, Roll-up summary

Read on the site: https://www.forcechallenges.com/notes/formulas-validation

## Formula fields

Read-only, calculated on the fly, never stored.

```text
// Weighted pipeline (Currency)
Amount * Probability / 100

// Days open (Number) on Case
IF(IsClosed, ClosedDate - CreatedDate, NOW() - CreatedDate)

// Cross-object: Contact → Account (up to 10 relationships away)
Account.Owner.Email

// Text with picklist
CASE(Rating, "Hot", "🔥 Priority", "Warm", "Follow up", "Low")

// Picklist values must use ISPICKVAL / TEXT
IF(ISPICKVAL(StageName, "Closed Won"), "Won", "Open")
```

Useful functions: `IF`, `CASE`, `AND`, `OR`, `NOT`, `ISBLANK`, `BLANKVALUE`, `TEXT`, `VALUE`, `TODAY()`, `NOW()`, `ADDMONTHS`, `LEFT`, `CONTAINS`, `HYPERLINK`, `IMAGE`.

## Validation rules

The formula describes the **error condition** — when it evaluates to `TRUE`, the save is blocked.

```text
// Close date can't be in the past for open deals
AND(NOT(IsClosed), CloseDate < TODAY())

// Amount required once the deal reaches Proposal
AND(ISPICKVAL(StageName, "Proposal/Price Quote"), ISBLANK(Amount))

// Stage can't move backwards from Closed Won
AND(ISCHANGED(StageName), ISPICKVAL(PRIORVALUE(StageName), "Closed Won"))

// Indian PIN code must be 6 digits
AND(NOT(ISBLANK(BillingPostalCode)), NOT(REGEX(BillingPostalCode, "\\d{6}")))

// Only System Administrators may change the Account owner
AND(ISCHANGED(OwnerId), $Profile.Name <> "System Administrator")
```

Tips:
- Show the error **at a field** for better UX.
- `ISCHANGED` / `PRIORVALUE` work only on edit (not insert); use `ISNEW()` for insert-only rules.
- Validation rules also block **API, Data Loader and Apex** saves — remember data loads.
- Bypass pattern: a custom permission checked with `$Permission.Bypass_Validation`.

## Roll-up summary fields

On the **master** side of a master-detail relationship: `COUNT`, `SUM`, `MIN`, `MAX` of child records, with optional filter criteria.

*Example:* `Total_Won__c` on Account = SUM of Opportunity Amount where Stage = Closed Won. (Account–Opportunity is a special standard relationship that allows this.)

For a **lookup** relationship you need a record-triggered **Flow** or an **Apex trigger** (see the Roll Up Contact Count challenge).

## Interview questions

1. *Write a validation rule so Close Date can't be in the past.* → `CloseDate < TODAY()` (for open deals).
2. *Formula vs roll-up summary?* → Formula: values on the same/parent record. Roll-up: aggregate of children (master-detail only).
3. *Why does my data load fail after adding a validation rule?* → Rules apply to API loads too.

---
Source: ForceChallenges · last updated 2026-10-03
