Data Validation
Data validation applies rules to cells and checks entered values against them. It catches input errors early and keeps the data in a sheet accurate and consistent.
Univer supports the following validation types:
- Number
- Integer
- Text length
- Date
- Checkbox
- Dropdown list (single/multiple selection)
- Custom formula
Plugin mode
Installation
pnpm add @univerjs/data-validation @univerjs/sheets-data-validation @univerjs/sheets-data-validation-uinpm install @univerjs/data-validation @univerjs/sheets-data-validation @univerjs/sheets-data-validation-uiyarn add @univerjs/data-validation @univerjs/sheets-data-validation @univerjs/sheets-data-validation-uibun add @univerjs/data-validation @univerjs/sheets-data-validation @univerjs/sheets-data-validation-uiUsage
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'import { UniverDataValidationPlugin } from '@univerjs/data-validation'import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation'import { UniverSheetsDataValidationUIPlugin } from '@univerjs/sheets-data-validation-ui'import SheetsDataValidationEnUS from '@univerjs/sheets-data-validation-ui/locale/en-US'import '@univerjs/sheets-data-validation-ui/lib/index.css'import '@univerjs/sheets-data-validation/facade'const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( SheetsDataValidationEnUS, ), },})univer.registerPlugin(UniverDataValidationPlugin)univer.registerPlugin(UniverSheetsDataValidationPlugin)univer.registerPlugin(UniverSheetsDataValidationUIPlugin)Plugin configuration
UniverSheetsDataValidationUIPlugin
showEditOnDropdownbooleanDefault:trueShow the edit button in the list dropdown.showSearchOnDropdownbooleanDefault:trueShow the search box in the list dropdown.
univer.registerPlugin(UniverSheetsDataValidationUIPlugin, { /** * Whether to display the edit button in the drop-down menu * @default true */ showEditOnDropdown: true, /** * Whether to display the search box in the drop-down menu * @default true */ showSearchOnDropdown: true,})For all available options, see IUniverSheetsDataValidationUIConfig.
Mobile support
Configure the mobile editor first. In this page's plugin-mode setup, replace the desktop registrations below with the mobile exports from the same packages, and complete the replacement before opening a document. Keep the model plugins, styles, locales, and Facade imports, and do not register both variants.
| Package | Desktop registration | Mobile registration |
|---|---|---|
@univerjs/sheets-data-validation-ui | UniverSheetsDataValidationUIPlugin | UniverSheetsDataValidationMobileUIPlugin |
Preset mode
Installation
pnpm add @univerjs/preset-sheets-data-validationnpm install @univerjs/preset-sheets-data-validationyarn add @univerjs/preset-sheets-data-validationbun add @univerjs/preset-sheets-data-validationUsage
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'import { UniverSheetsDataValidationPreset } from '@univerjs/preset-sheets-data-validation'import UniverPresetSheetsDataValidationEnUS from '@univerjs/preset-sheets-data-validation/locales/en-US'import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'import '@univerjs/preset-sheets-core/lib/index.css'import '@univerjs/preset-sheets-data-validation/lib/index.css'const { univerAPI } = createUniver({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( UniverPresetSheetsCoreEnUS, UniverPresetSheetsDataValidationEnUS, ), }, presets: [ UniverSheetsCorePreset(), UniverSheetsDataValidationPreset(), ],})Preset configuration
UniverSheetsDataValidationPreset
showEditOnDropdownbooleanDefault:trueShow the edit button in the list dropdown.showSearchOnDropdownbooleanDefault:trueShow the search box in the list dropdown.
UniverSheetsDataValidationPreset({ /** * Whether to display the edit button in the drop-down menu * @default true */ showEditOnDropdown: true, /** * Whether to display the search box in the drop-down menu * @default true */ showSearchOnDropdown: true,})For all available options, see IUniverSheetsDataValidationPresetConfig.
Value matching
List validation ignores case, so green satisfies an option written Green, and a referenced list follows the same rule. Number and integer rules accept numeric text only. Booleans and blank text do not satisfy them.
Facade API
Complete Facade API type definitions are in FacadeAPI.
Importing
Plugin mode note
The Facade package is imported manually only in plugin mode. Preset mode already includes the matching package, so no additional import is required.
import '@univerjs/sheets-data-validation/facade'Add a data validation rule
univerAPI.newDataValidation() creates a builder and returns an FDataValidationBuilder. Call its methods in a chain to construct the rule.
The main methods on FDataValidationBuilder are:
| Method | Description |
|---|---|
| build | Build the rule. |
| requireCheckbox | Require a boolean value, which the cell displays as a checkbox. |
| requireDateAfter | Set the type to DATE and require a date after the given date. |
| requireDateBefore | Set the type to DATE and require a date before the given date. |
| requireDateBetween | Set the type to DATE and require a date within the given range. |
| requireDateEqualTo | Set the type to DATE and require a date equal to the given date. |
| requireDateNotBetween | Set the type to DATE and require a date outside the given range. |
| requireDateOnOrAfter | Set the type to DATE and require a date on or after the given date. |
| requireDateOnOrBefore | Set the type to DATE and require a date on or before the given date. |
| requireFormulaSatisfied | Require the given formula to evaluate to true. |
| requireNumberBetween | Require a number between the two given numbers, inclusive. |
| requireNumberEqualTo | Require a number equal to the given value. |
| requireNumberGreaterThan | Require a number greater than the given value. |
| requireNumberGreaterThanOrEqualTo | Require a number greater than or equal to the given value. |
| requireNumberLessThan | Require a number less than the given value. |
| requireNumberLessThanOrEqualTo | Require a number less than or equal to the given value. |
| requireNumberNotBetween | Require a number that is not between the two given numbers and not equal to either. |
| requireNumberNotEqualTo | Require a number not equal to the given value. |
| requireValueInList | Require a value from a list of specific values. Supports single/multiple selection and showing or hiding the dropdown. |
| requireValueInRange | Require a value within a specific range. Supports single/multiple selection and showing or hiding the dropdown. |
| setOptions | Set the options for the rule. |
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Create a new data validation rule that requires a number between 1 and 10 for the range A1:B10const fRange = fWorksheet.getRange('A1:B10')const rule = univerAPI.newDataValidation() .requireNumberBetween(1, 10) .setOptions({ allowBlank: true, showErrorMessage: true, error: 'Please enter a number between 1 and 10', }) .build()fRange.setDataValidation(rule)Clear data validations of a range
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Clear data validation of range A1:B10const fRange = fWorksheet.getRange('A1:B10')fRange.setDataValidation(null)Get data validations of range / worksheet
The returned rule object is an FDataValidation instance, which exposes the rule's criteria, options, and other settings.
The main methods on FDataValidation are:
| Method | Description |
|---|---|
| copy | Create a new FDataValidationBuilder instance from the current rule object. |
| getCriteriaType | Get the rule's validation type. |
| getCriteriaValues | Get the values used to evaluate the criteria. |
| getHelpText | Get the help text, which provides guidance to users. |
| getRanges | Get the ranges the rule applies to. |
| setCriteria | Set the rule's criteria. |
| setOptions | Set the rule's options. |
| setRanges | Set the ranges the rule applies to. |
| delete | Delete the rule from the worksheet. |
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Get all data validation rules in current sheet.const rulesOfSheet = fWorksheet.getDataValidations()// Get a data validation rule by rule ID.const ruleById = fWorksheet.getDataValidation(rulesOfSheet[0]?.rule?.uid)const fRange = fWorksheet.getRange('A1:B10')// Get first data validation rule in current range.const ruleOfRange = fRange.getDataValidation()console.log('ruleOfRange:', ruleOfRange, ruleOfRange?.getCriteriaValues())// Get all data validation rules in current range.const rulesOfRange = fRange.getDataValidations()Update/Delete data validation
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Create a new data validation rule that requires a number equal to 20 for the range A1:B10const fRange = fWorksheet.getRange('A1:B10')const rule = univerAPI.newDataValidation() .requireNumberEqualTo(20) .build()fRange.setDataValidation(rule)const newRuleRange = fWorksheet.getRange('C1:D10')// Update the rule after 3 secondssetTimeout(() => { fRange.getDataValidation() // Change the range to C1:D10 .setRanges([newRuleRange]) // Change the criteria to require a number between 1 and 10 .setCriteria( univerAPI.Enum.DataValidationType.DECIMAL, [univerAPI.Enum.DataValidationOperator.BETWEEN, '1', '10'], ) // Change option to stop input on validation errors and show error message .setOptions({ allowBlank: true, showErrorMessage: true, error: 'Please enter a valid value', errorStyle: univerAPI.Enum.DataValidationErrorStyle.STOP, })}, 3000)// Delete the rule after 6 secondssetTimeout(() => { newRuleRange.getDataValidation().delete()}, 6000)Get validation errors
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Get all data validation errors for current workbook.const workbookErrors = await fWorkbook.getAllDataValidationErrorAsync()console.log('workbookErrors:', workbookErrors)// Get all data validation errors for current sheet.const worksheetErrors = await fWorksheet.getAllDataValidationErrorAsync()console.log('worksheetErrors:', worksheetErrors)// Get data validation errors for current range.const fRange = fWorksheet.getRange('A1:B10')const rangeErrors = await fRange.getDataValidationErrorAsync()console.log('rangeErrors:', rangeErrors)Each error object contains the following fields:
sheetName: Name of the worksheet where the error occurredrow: Row index of the cell that triggered the errorcolumn: Column index of the cell that triggered the errorruleId: ID of the rule that triggered the errorinputValue: Input value that triggered the errorrule: Snapshot of the rule content
Get validator status
Validator status is a value of the DataValidationStatus enum:
valid: The cell value passes validationinvalid: The cell value fails validationvalidating: The cell is being validated
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Get data validation validator status for current workbook.fWorkbook.getValidatorStatus().then((status) => { console.log('===statusOfWorkbook', status)})// Get data validation validator status for current sheet.fWorksheet.getValidatorStatusAsync().then((status) => {})// Get data validation validator status for current range.const fRange = fWorksheet.getRange('A1:B10')fRange.getValidatorStatus().then((status) => { console.log('===tatusOfRange', status)})Event listeners
Complete event type definitions are in Events.
The data validation module emits events when rules are added, updated, or deleted, and when validation status changes. Use univerAPI.addEvent() to listen to any of these events.
Validation rule change events
univerAPI.Event.SheetDataValidationChanged fires after a validation rule changes.
const disposable = univerAPI.addEvent(univerAPI.Event.SheetDataValidationChanged, (params) => { const { origin, worksheet, workbook, changeType, oldRule, rule } = params})// Remove the event listener, use `disposable.dispose()`univerAPI.Event.BeforeSheetDataValidationAdd fires before a rule is added.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationAdd, (params) => { const { worksheet, workbook, rule } = params // Cancel the data validation rule addition operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`univerAPI.Event.BeforeSheetDataValidationDelete fires before a rule is deleted.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationDelete, (params) => { const { worksheet, workbook, ruleId, rule } = params // Cancel the data validation rule deletion operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`univerAPI.Event.BeforeSheetDataValidationDeleteAll fires before all rules are deleted.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationDeleteAll, (params) => { const { worksheet, workbook, rules } = params // Cancel the data validation rule deletion operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`Validation rule update events
univerAPI.Event.BeforeSheetDataValidationCriteriaUpdate fires before a rule's criteria change.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationCriteriaUpdate, (params) => { const { worksheet, workbook, ruleId, rule, newCriteria } = params // Cancel the data validation rule criteria update operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`univerAPI.Event.BeforeSheetDataValidationRangeUpdate fires before a rule's ranges change.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationRangeUpdate, (params) => { const { worksheet, workbook, ruleId, rule, newRanges } = params // Cancel the data validation rule range update operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`univerAPI.Event.BeforeSheetDataValidationOptionsUpdate fires before a rule's options change.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationOptionsUpdate, (params) => { const { worksheet, workbook, ruleId, rule, newOptions } = params // Cancel the data validation rule options update operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`Validation status events
univerAPI.Event.SheetDataValidatorStatusChanged fires when a cell's validation status changes.
const disposable = univerAPI.addEvent(univerAPI.Event.SheetDataValidatorStatusChanged, (params) => { const { worksheet, workbook, row, column, status, rule } = params})// Remove the event listener, use `disposable.dispose()`Every event includes the following common parameters:
workbook: Current workbook instanceworksheet: Current worksheet instance
Some events also include:
rule: The related validation rule objectruleId: Unique identifier of the rulestatus: Validation status (only inSheetDataValidatorStatusChanged)newCriteria: New validation criteria (only inBeforeSheetDataValidationCriteriaUpdate)newRanges: New validation ranges (only inBeforeSheetDataValidationRangeUpdate)newOptions: New validation options (only inBeforeSheetDataValidationOptionsUpdate)
For any event whose name begins with Before, set params.cancel = true in the callback to stop the operation.
Error style
errorStyle controls what happens when invalid data is entered. It accepts a DataValidationErrorStyle value:
STOP: Rejects the invalid entryWARNING: Accepts the invalid entry and shows a warningINFO: Accepts the invalid entry and shows an information message
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B10')const rule = univerAPI.newDataValidation() .requireNumberBetween(1, 10) .setOptions({ allowBlank: true, showErrorMessage: true, error: 'Please enter a number between 1 and 10', errorStyle: univerAPI.Enum.DataValidationErrorStyle.STOP, }) .build()fRange.setDataValidation(rule)Change list render mode
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B10')fRange.getDataValidation()?.setOptions({ // support TEXT, ARROW, CUSTOM // default is `CUSTOM` renderMode: univerAPI.Enum.DataValidationRenderMode.TEXT,})How is this guide?