Sub topic 12
Set Validation Rules with Apps Script
You can build every rule from the earlier chapters by hand in the Data validation dialog. Apps Script does the same work in code, which pays off when you need to set up many sheets the same way, rebuild rules after someone damages them, or audit what rules exist. This chapter assumes you have already used the dialog to make drop-downs, number and date rules, and custom formula rules. It also assumes you can open Extensions > Apps Script and run a function, and that you understand relative and absolute references such as A2 and $A$2.
How a rule is built
A script never edits a rule in place. It builds a new rule object and assigns it to a range. The process has three steps:
- Call
SpreadsheetApp.newDataValidation()to get a builder. - Chain one
require...method to choose the criteria, then any options such assetAllowInvalid()andsetHelpText(). - Call
build()to get a rule, then pass the rule tosetDataValidation()on a range.
A range can hold only one rule per cell. Assigning a new rule to a range replaces whatever rule was there.
A drop-down from typed items
This function applies a three-item drop-down to C2:C100, rejects any other value, and shows help text.
function addStatusDropdown() {
const sheet = SpreadsheetApp.getActiveSheet();
const rule = SpreadsheetApp.newDataValidation()
.requireValueInList(['Not started', 'In progress', 'Done'], true)
.setAllowInvalid(false)
.setHelpText('Pick a status from the list.')
.build();
sheet.getRange('C2:C100').setDataValidation(rule);
}The second argument of requireValueInList controls whether the in-cell arrow appears. Passing false keeps the rule but hides the drop-down, so users must type a matching value.
Matching in a list rule is exact on the text, and the list items are plain strings. If you pass a number such as 1, the script stores it as the text of the item, which can surprise you when you compare it against numeric cells. Pass items as strings and keep your data in the same form.
A drop-down from a range
To read options from cells, use requireValueInRange. It takes a Range object, not an A1 string, and the range can sit on another sheet.
function addCategoryDropdown() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const source = ss.getSheetByName('Lists').getRange('A2:A20');
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(source, true)
.setAllowInvalid(false)
.build();
ss.getSheetByName('Data').getRange('B2:B100').setDataValidation(rule);
}The rule points at the cells, so editing Lists!A2:A20 changes the options without rerunning the script. Adding an item below row 20 does not extend the list, because the rule captured the range A2:A20. If the list will grow, give the source range spare empty rows, or rerun the script with a larger range. Empty cells in the source do not appear as options.
Reject or warn
setAllowInvalid is the script version of the dialog's "Reject the input" and "Show a warning" choices:
| Call | Behavior when a typed value fails the rule |
|---|---|
| `setAllowInvalid(false)` | The edit is rejected and the cell keeps its old value. |
| `setAllowInvalid(true)` | The edit is accepted. The cell gets a red corner marker and a warning on hover. |
Number, date, text and checkbox rules
Each criterion has its own require method. Here is a function that sets several of them on different columns.
function addTypedRules() {
const sheet = SpreadsheetApp.getActiveSheet();
const quantityRule = SpreadsheetApp.newDataValidation()
.requireNumberBetween(1, 100)
.setAllowInvalid(false)
.setHelpText('Enter a number from 1 to 100.')
.build();
sheet.getRange('D2:D100').setDataValidation(quantityRule);
const emailRule = SpreadsheetApp.newDataValidation()
.requireTextIsEmail()
.setAllowInvalid(false)
.setHelpText('Enter a valid email address.')
.build();
sheet.getRange('E2:E100').setDataValidation(emailRule);
const doneRule = SpreadsheetApp.newDataValidation()
.requireCheckbox()
.build();
sheet.getRange('F2:F100').setDataValidation(doneRule);
}Other methods follow the same naming pattern. Examples are requireNumberGreaterThan, requireNumberLessThanOrEqualTo, requireTextContains, requireTextIsUrl, requireDate, requireDateAfter and requireDateOnOrBefore. Check the DataValidationBuilder reference for the full list.
requireCheckbox() with no arguments makes a standard TRUE/FALSE checkbox. Passing one argument sets the checked value, and passing two sets both the checked and unchecked values, for example requireCheckbox('Yes', 'No').
Dates are fixed when the script runs
Date methods take JavaScript Date objects. That includes new Date():
function addDateRuleFixed() {
const rule = SpreadsheetApp.newDataValidation()
.requireDateBetween(new Date(2025, 0, 1), new Date())
.setAllowInvalid(false)
.build();
SpreadsheetApp.getActiveSheet().getRange('B2:B100').setDataValidation(rule);
}The upper limit here is the day the script ran. Tomorrow, a valid date entered tomorrow will be rejected. A rule that must always mean "up to today" needs a formula that calls TODAY(), which is evaluated each time a cell is edited. Use a custom formula rule for that case.
Custom formula rules
requireFormulaSatisfied takes a formula string that must evaluate to TRUE for the value to be accepted. Write it as if you were typing it for the top-left cell of the range. Sheets shifts the relative references for the other cells, exactly as the dialog does.
function addUniqueAndDateFormulas() {
const sheet = SpreadsheetApp.getActiveSheet();
const uniqueRule = SpreadsheetApp.newDataValidation()
.requireFormulaSatisfied('=COUNTIF($A$2:$A$100, A2)=1')
.setAllowInvalid(false)
.setHelpText('This value already exists in the column.')
.build();
sheet.getRange('A2:A100').setDataValidation(uniqueRule);
const dateRule = SpreadsheetApp.newDataValidation()
.requireFormulaSatisfied('=AND(ISNUMBER(B2), B2>=DATE(2025,1,1), B2<=TODAY())')
.setAllowInvalid(false)
.setHelpText('Enter a date from 1 January 2025 up to today.')
.build();
sheet.getRange('B2:B100').setDataValidation(dateRule);
}The first rule uses $A$2:$A$100, which stays fixed, and A2, which moves down one row for each cell. If you write $A$2 where you meant A2, every cell compares against the same value and the rule behaves wrongly. Check the first cell's rule in the dialog after running the script, and confirm the formula text matches what you intended.
Dependent drop-downs
A dependent drop-down has no dedicated method. You build it from pieces you already know. A helper cell holds a FILTER formula that returns the items for the category chosen in A2:
=FILTER(Lists!B2:B, Lists!A2:A=A2)The script then points a range-based rule at the cells that hold those items:
function addDependentDropdown() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const helper = ss.getSheetByName('Lists').getRange('E2:E20');
const rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(helper, true)
.setAllowInvalid(false)
.build();
ss.getSheetByName('Data').getRange('B2').setDataValidation(rule);
}This works for a single row because the helper range is tied to the category in A2. Handling many rows takes one helper block per row or a different approach, which is beyond what a static rule can do.
Reading and copying rules
Scripts can inspect rules, which is useful for audits.
function listRules() {
const range = SpreadsheetApp.getActiveSheet().getRange('C2:C100');
const rules = range.getDataValidations();
rules.forEach(function (row, i) {
const rule = row[0];
if (rule) {
Logger.log('C' + (i + 2) + ': ' + rule.getCriteriaType() +
', rejects invalid input: ' + !rule.getAllowInvalid());
}
});
}getDataValidations() returns a two-dimensional array with one entry per cell, and an entry is null where the cell has no rule. getDataValidation() without the plural returns only the rule of the top-left cell.
To copy a rule to other cells, read it and assign it. To copy it with a change, use copy(), which returns a builder:
function copyRuleWithChange() {
const sheet = SpreadsheetApp.getActiveSheet();
const rule = sheet.getRange('C2').getDataValidation();
if (rule === null) {
return;
}
const warnOnly = rule.copy().setAllowInvalid(true).build();
sheet.getRange('G2:G100').setDataValidation(warnOnly);
}When you need different rules in different cells, build a two-dimensional array of rules with the same shape as the range and call setDataValidations(rules) once. That is one call instead of many, and it runs faster on large ranges.
Removing rules
This function removes the validation rules from C2:C100 without deleting the values in those cells.
function clearStatusValidation() {
SpreadsheetApp.getActiveSheet().getRange('C2:C100').clearDataValidations();
}Existing values stay as they are, including values that would no longer pass. Removing a rule also removes the drop-down arrow or checkbox appearance that the rule produced.
What scripts do not protect against
Validation is checked when a person edits a cell in the interface. Several paths skip it:
- A script that calls
setValue()orsetValues()writes any value, even into a cell with a reject rule. If your script writes data, check the value in code before writing. - Pasting a value over a validated cell replaces the rule along with the value in many cases, depending on how the paste is done.
- Values that were in the cells before you applied the rule are not checked. A red corner marker appears only after someone edits or revisits the cell.
- Anyone with edit access can open the dialog and remove the rule.
For data that must be clean, treat validation as a guide for honest users, and add a script or formula check that reports bad rows.
Common errors
| Symptom | Likely cause |
|---|---|
| Bad values still get in | `setAllowInvalid(false)` was not called, so the rule only warns. |
| `Cannot find method requireValueInRange(string)` | You passed an A1 string. Pass a `Range` object. |
| Formula rule checks the wrong cells | A relative reference was written as absolute, or the formula was written for a cell other than the top-left one. |
| Date limit stops working over time | The date came from `new Date()` at run time. Use a `TODAY()` formula rule instead. |
| New list items missing from the drop-down | The source range was fixed and does not cover the new rows. |
| Old rule still present after rerun | Rules apply per range. A different range from the earlier run was not cleared. |
Exercise
Write a function that applies a rule to H2:H50 that accepts only whole-number-looking values between 0 and 10 and rejects everything else, with help text "Score from 0 to 10." Then say what happens if you leave out setAllowInvalid.
Show answer
function addScoreRule() { const rule = SpreadsheetApp.newDataValidation() .requireNumberBetween(0, 10) .setAllowInvalid(false) .setHelpText('Score from 0 to 10.') .build(); SpreadsheetApp.getActiveSheet().getRange('H2:H50').setDataValidation(rule); } Without setAllowInvalid(false), the default is true, so an out-of-range value is accepted and only flagged with a warning marker. Note that requireNumberBetween also accepts decimals such as 4.5, so a whole-number requirement needs a custom formula such as =AND(ISNUMBER(H2), H2=INT(H2), H2>=0, H2<=10).
Exercise
A script writes the text "Maybe" into a cell in C2:C100 that has the status drop-down rule from addStatusDropdown, using setValue. Is the value rejected? How would you find such values afterward?
Show answer
No. Validation applies to edits made in the interface, and setValue writes the value regardless of the rule. To find such values, read the range with getValues() and compare each against the allowed list in code, or add a helper column with a formula such as =COUNTIF({"Not started","In progress","Done"}, C2)=0 to flag the bad rows.