Sub topic 9
Write Custom Formula Rules
Built-in criteria cover many cases, such as "number between 1 and 10" or "text contains". They cannot express a rule that depends on other cells, on the rest of the column, or on a combination of conditions. Custom formula rules can. This chapter explains how Google Sheets evaluates them, walks through the patterns you will use most, and covers the errors that cause rules to fail without any warning.
Prerequisites
This chapter assumes you can do the following:
- Select cells and ranges in Google Sheets.
- Enter values and basic formulas.
- Use absolute and relative references, such as
A2and$A$2. - Refer to another sheet in a formula.
You should also know how to open Data > Data validation and choose between rejecting input and showing a warning. Both options apply to custom formula rules.
How a custom formula rule works
In the data validation panel, add a rule and set the criteria to Custom formula is. You then type a formula that Sheets evaluates for each cell in the rule's range.
- If the formula returns
TRUE, the entry is valid. - If it returns
FALSE, the entry is invalid. Sheets then rejects it or shows a warning, depending on your invalid-input setting.
The formula must produce a boolean. Sheets also treats a non-zero number as TRUE and 0 as FALSE. For clarity, write comparisons that return TRUE or FALSE directly.
Write the formula for the first cell
Write the formula as if it were in the top-left cell of the range. Sheets adjusts relative references for every other cell, in the same way it adjusts a copied formula.
Suppose the rule applies to A2:A100. You write the formula for A2. When Sheets checks A7, it reads your reference to A2 as A7. Your reference to $A$2:$A$100 stays fixed.
This is the most common source of errors. The next section shows both sides of it.
Pattern 1: prevent duplicate entries
To keep every entry in a column unique, apply this rule to A2:A100:
=COUNTIF($A$2:$A$100, A2)=1Here is how it works:
$A$2:$A$100is the full range to search. The dollar signs fix it, so it does not shift from cell to cell.A2is relative. Sheets changes it toA3,A4, and so on.COUNTIFcounts how many cells in the range equal the entered value.- When the count is exactly 1, the value appears only in this cell, so it is unique.
If you type a value that already exists, the count becomes 2 and the rule fails.
Edge cases
- Blank cells.
COUNTIFof an empty cell returns the number of blank cells in the range, which is usually more than 1. If you clear a cell, Sheets does not re-validate it as a new entry, so this rarely causes trouble. If it does, wrap the test:=OR(A2="", COUNTIF($A$2:$A$100, A2)=1). - Case.
COUNTIFignores case, soAppleandapplecount as duplicates. - Wildcards.
COUNTIFtreats*and?in the search value as wildcards, and~as an escape. Enteringa*can match many cells. For IDs that may contain these characters, useSUMPRODUCT(--($A$2:$A$100=A2))=1instead, which compares literally. - Numbers and text.
COUNTIFcan treat the text"1"and the number1as the same value. Be consistent about the type you store.
Pattern 2: restrict dates to a window
To accept only dates from 1 January 2025 up to today, apply this rule to B2:B100:
=AND(ISNUMBER(B2), B2>=DATE(2025,1,1), B2<=TODAY())AND returns TRUE only when every test passes:
ISNUMBER(B2)confirms the entry is a real date. Sheets stores dates as numbers, so typed text such assoonfails here.B2>=DATE(2025,1,1)sets the lower limit.B2<=TODAY()sets a moving upper limit.
The built-in "Date is between" criterion can also accept TODAY()-style values through its date options. The custom formula is useful when you want one rule that checks type and range together, or when the limits come from other cells. For example, replace DATE(2025,1,1) with $F$1, and users can change the start date without editing the rule.
Edge cases
TODAY()recalculates when the sheet opens or changes. A date that was valid yesterday remains in the cell even if a rule would reject it today, because validation only runs on entry.- Entries typed in a different locale format, such as
03/04/2025, are parsed according to the spreadsheet's locale. Check the locale under File > Settings if dates are being misread.
Pattern 3: depend on another cell
A custom formula can look at other cells in the same row. Suppose column C holds a quantity and column D holds a discount. You want the discount to be allowed only when the quantity is at least 10. Apply this rule to D2:D100:
=OR(D2="", C2>=10)Here C2 is relative, so each row checks its own quantity. The D2="" clause lets a blank discount through.
A related rule requires a note when a status is Rejected. Apply this to E2:E100:
=OR(D2<>"Rejected", E2<>"")This reads: "either the status is not Rejected, or the note is filled in."
Be aware of a limit here. Validation checks the cell being edited. If someone changes C2 after entering the discount, the discount in D2 is not rechecked. To flag such cases afterward, use conditional formatting with the same formula, negated. This catches data that was valid when entered but is no longer valid.
Pattern 4: a dependent list through a helper cell
Custom formulas decide whether a value is valid. Dependent drop-downs, where the options in one cell change with another, need a small addition. The drop-down must point at a range, and that range comes from a formula.
Put this in a helper cell, for example Lists!D2, where A2 on the active sheet holds the chosen category:
=FILTER(Lists!B2:B, Lists!A2:A=A2)This returns the items from Lists!B2:B whose category in Lists!A2:A equals A2. The result spills downward from the helper cell. A drop-down in B2 then uses Dropdown (from a range) and points at the cells that hold that spilled result.
Two points matter in practice:
- A drop-down range does not follow a spill automatically. Point it at a range large enough for the longest list, such as
Lists!D2:D50. Empty cells at the end are ignored in the drop-down. - A helper cell can only serve one row. For a column of dependent drop-downs, each row needs its own helper block, or you need a different design. The dependent drop-downs chapter covers this in detail.
Because the helper formula references A2 on a different sheet than the one being validated, use a sheet name in the reference as shown. Without the Lists! prefix, Sheets looks on the current sheet.
Choosing between a built-in and a custom rule
| Need | Prefer | Reason |
|---|---|---|
| Number in a fixed range | Built-in "Number between" | Simpler, and the rule is readable in the panel |
| Text contains or equals a value | Built-in text criteria | No formula to maintain |
| Valid email or URL | Built-in "Valid email" or "Valid URL" | Handles the format checks for you |
| Unique values in a column | Custom formula | No built-in criterion exists |
| Rule depends on another cell | Custom formula | Built-ins cannot reference neighbors reliably |
| Several conditions at once | Custom formula | Combine with `AND` and `OR` |
Common errors and how to diagnose them
The rule rejects everything, or nothing
The usual cause is a reference problem. Test it this way:
- Write your formula in an ordinary cell next to the data, in the same row as the first cell of the range.
- Fill it down and check that each row shows
TRUEorFALSEas you expect. - Move the working formula into the rule.
If the test cells give the right answers but the rule does not, check whether the rule's range starts at the row your formula refers to. A rule on A3:A100 written as if for A2 will be off by one row.
Missing dollar signs
Writing COUNTIF(A2:A100, A2)=1 leaves the range relative. For A3 the range becomes A3:A101. That excludes the rows above and extends past your data. Anchor the search range with $.
Referencing another sheet
Older behavior blocked direct references to other sheets in some validation rules. Current Google Sheets accepts them in custom formulas. If a rule with a cross-sheet reference fails or you work in a file that behaves differently, wrap the reference in INDIRECT, for example COUNTIF(INDIRECT("Lists!A2:A100"), A2)>0. INDIRECT works but is volatile and breaks if the sheet is renamed.
The formula is accepted but never triggers
Check that the invalid-input option is not set to a state where you cannot see the result. With Show a warning, the entry is kept and a small red triangle marks the cell. With Reject the input, a message appears and the value is refused.
Text that looks valid
Entries with leading or trailing spaces differ from the clean text. "Done " does not equal "Done". If this matters, test the trimmed value: =TRIM(A2)=A2.
Set a custom rule with Apps Script
You can also create a custom formula rule in code, which helps when you apply the same rule to many sheets. This function applies the duplicate-prevention rule to A2:A100:
function addUniqueRule() {
const sheet = SpreadsheetApp.getActiveSheet();
const rule = SpreadsheetApp.newDataValidation()
.requireFormulaSatisfied('=COUNTIF($A$2:$A$100, A2)=1')
.setAllowInvalid(false)
.setHelpText('This value already exists. Enter a unique value.')
.build();
sheet.getRange('A2:A100').setDataValidation(rule);
}As in the panel, the formula is written for the first cell of the range. setAllowInvalid(false) rejects invalid input, and true shows a warning instead.
What custom rules do not protect against
Custom formula rules share the limits of all validation:
- Pasted values. Pasting a value from another cell or source can replace the validation rule or bypass it. Pasting with Paste special > Values only keeps the target rule in many cases, but you cannot count on that.
- Existing data. A rule checks new entries. Values already in the range are not changed, and invalid ones are not removed. Use conditional formatting to highlight them.
- Other cells changing. As shown in pattern 3, a rule does not re-run when a cell it refers to changes.
- Scripts and imports. Values written by Apps Script, imports, or formulas are not subject to the rule.
Summary
- A custom formula rule returns
TRUEfor valid entries andFALSEfor invalid ones. - Write the formula for the top-left cell of the range. Relative references shift for other cells, and
$references stay fixed. COUNTIF($A$2:$A$100, A2)=1enforces unique entries.ANDcombines several date or type tests.- Validation runs on entry only. It does not re-check when related cells change, and it does not stop every paste.
Exercise
A rule is applied to C2:C50 with the formula =COUNTIF(C2:C50, C2)=1. The first few entries pass, but later duplicates are accepted. Why does this happen, and what is the corrected formula?
Show answer
The search range C2:C50 has no dollar signs, so it shifts for each cell. For C3 it becomes C3:C51, and for C10 it becomes C10:C58. The range then no longer covers the earlier rows where the duplicate sits. The corrected formula anchors the range: =COUNTIF($C$2:$C$50, C2)=1.
Exercise
Write a custom formula rule for F2:F100 that accepts a value only when column E in the same row is not empty. Blank entries in column F should also be allowed.
Show answer
=OR(F2="", E2<>""). The formula is written for the first cell, F2, and E2 is relative, so each row checks its own column E cell. The F2="" clause allows blank entries.
Exercise
You set the rule =AND(ISNUMBER(B2), B2<=TODAY()) on a date column. A user pastes a future date from another sheet and it is accepted. Name two reasons this can happen.
Show answer
Pasting can replace or bypass the validation rule on the target cell, so the formula never runs. Also, validation only checks values typed or chosen in the cell, not values written by scripts or imports. To catch such entries, use conditional formatting with the negated formula, such as =NOT(AND(ISNUMBER(B2), B2<=TODAY())).