gridcn2.0.0
Editing cells

Validation

Reject a cell value before it commits with a function or a schema, and flag soft rules.

A column's validate rejects a value before it enters data. It takes a function or a Standard Schema. It runs on a typed edit, a checkbox toggle, paste, fill, updateCells, updateRows, editRows, find and replace, import, Delete, and Cut. Live columns for each form are in the validation example. To check a whole row or wait for an async schema, see Row validation and async checks.

ColumnRuleKind
Age18 or older. Also fires a toast.Blocking
EmailMust contain an @.Blocking
SKUSKU-001 and SKU-002 are taken. The check takes about 800 ms and the input is read-only meanwhile.Blocking
PriceMust be a number. A decimal commits rounded: 42.9 becomes 43.Blocking
NotesAt most 12 characters.Soft
Zod ScoreInteger from 0 to 100.Blocking
Joi CodeUppercase letters, digits, or dashes.Blocking
Valibot TagAt least 3 characters.Blocking
  • Every message: hover the cell to read it, also while the editor is open (the browser shows it as a native tooltip).
  • Blocking rule: Enter, Tab, or a click on another cell keeps the editor open, and the value does not commit. The message also shows in a line next to the cell. Escape cancels the edit and restores the old value.
  • Soft rule (Notes): the value commits and the editor closes. The cell stays flagged. If you edit it again, the line shows next to the cell. A valid value clears the flag.
  • Paste: copy a column of ages (some under 18) and paste it onto Age. Valid cells commit and invalid cells drop. Notes drops its invalid cells on paste too.
Name
Age
Email
SKU
Price
Notes
Zod Score
Joi Code
Valibot Tag
Ada Lovelace
28
ada@example.com
SKU-101
42
First algorithm
87
ADA-1843
math
Grace Hopper
34
grace@example.com
SKU-102
18
Compiled it
94
GRACE-1906
compilers
Alan Turing
41
alan@example.com
SKU-103
99
Broke Enigma
99
TURING-1912
computability
Katherine Johnson
25
katherine@example.com
SKU-104
7
Trajectory math
91
KATH-1918
orbital
Margaret Hamilton
22
margaret@example.com
SKU-105
56
Apollo nav
96
MARG-1936
software
Radia Perlman
30
radia@example.com
SKU-106
31
Spanning trees
88
RADIA-1951
networking
Tim Berners-Lee
19
tim@example.com
SKU-107
64
Invented the web
98
TIM-1955
web
Barbara Liskov
45
barbara@example.com
SKU-108
12
Subtyping
93
BARB-1939
types

Validate a column

validate takes one of two forms:

  • A function (value, row, ctx) => string | null. Return a message to reject the value, or null to accept it. ctx holds three members. rows is the rows before the write. batch is every cell of the column that the same write sets. valueOf(row) is the column value of a row.
  • Any Standard Schema for the value, such as Zod, Valibot, or ArkType. The grid reads any schema with a "~standard" key.

A schema message joins its issues with "; " and prefixes an issue path as a.b: message.

A cell type can declare validate as a default for its columns. The type rule runs first, then the column rule. A schema on the cell type applies only to a column without its own validate. Undo and redo replay recorded changes and skip validate.

Install zod first with pnpm add zod. This grid uses both forms:

import { z } from "zod";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Person = { id: string; age: number; score: number };

const columns = defineColumns<Person>()([
  {
    id: "age",
    header: "Age",
    accessorKey: "age",
    type: "number",
    validate: (value) =>
      typeof value === "number" && value < 18 ? "Must be 18 or older" : null,
  },
  {
    id: "score",
    header: "Score",
    accessorKey: "score",
    type: "number",
    validate: z.number().int().min(0).max(100),
  },
]);

export function People({ people }: { people: Person[] }) {
  return <DataGrid defaultData={people} columns={columns} />;
}

Validate an email

This column rejects text that does not look like an email address. An empty cell passes, so the field stays optional:

import { defineColumns } from "@/components/data-grid/data-grid";

type Contact = { id: string; email: string };

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const columns = defineColumns<Contact>()([
  {
    id: "email",
    header: "Email",
    accessorKey: "email",
    validate: (value) =>
      typeof value === "string" && value !== "" && !EMAIL.test(value)
        ? "Enter an email such as name@example.com"
        : null,
  },
]);

A schema works too, for example validate: z.email() with Zod 4. Your server checks the address again, because the grid only checks the format.

The editor stays open on a rejected value and shows the message, and the value never enters data. A rejected checkbox toggle has no editor: the cell keeps its old value, and onValidationError reports it with the source "edit".

The message shows as an error line next to the open editor. The line escapes the cell and widens to its text, up to 16rem. It flips above the cell at the bottom edge of the grid. At the side edges, it anchors to the end side of the cell. An editing cell does not clip its content, so a custom Editor wider than its cell spills over the neighbors.

If a validator throws or its promise rejects, the grid rejects the value and shows the error message. A throwing validator blocks the edit even on a soft column.

Soft rules

By default a rejection blocks the commit. Set validationMode: "warn" to commit the value and flag the cell instead. The flag uses the same ring, tint, and hover tooltip as a server error. The next valid commit of that cell clears it. The editor closes, because the commit succeeded.

A soft rule follows these rules:

  • A rejection carries no transformed value, so a soft commit stores the raw input.
  • The flag works with the function form and with sync and async schemas.
  • Paste, fill, updateCells, import, Delete, and Cut also keep the raw value of a rejected cell in a soft column and flag it.
  • A validator that throws still blocks the cell.
  • A bulk write updates the flags once and calls no onValidationError for a flagged cell.
  • To drop rejected cells, use validationMode: "block" or processPaste.

This table compares a blocking rule with a soft rule:

BehaviorBlocking rule (default)Soft rule (validationMode: "warn")
Enter, Tab, or a click on another cellThe editor stays openThe editor closes
The valueStays out of the dataEnters the data as typed
Message on hoverYes, while the editor is openYes, always
Message in a line next to the cellYes, while the editor is openWhen the user edits the flagged cell again
EscapeCancels the edit and restores the old value. The error goes awayCancels the edit. A flagged cell keeps its flag
The error ends whenThe user commits a valid value, or cancels with EscapeThe user commits a valid value, or undoes the write
Paste and fillInvalid cells dropInvalid cells keep their value and carry a flag

For a value that must never reach your data, such as an amount, use a blocking rule. For a value that is allowed but needs a second look, such as a long note, use a soft rule.

This column flags a note over 12 characters:

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Note = { id: string; text: string };

const columns = defineColumns<Note>()([
  {
    id: "text",
    header: "Text",
    accessorKey: "text",
    validate: (value) =>
      typeof value === "string" && value.length > 12
        ? "Max 12 characters"
        : null,
    validationMode: "warn",
  },
]);

export function Notes({ notes }: { notes: Note[] }) {
  return <DataGrid defaultData={notes} columns={columns} />;
}

Transforms

A schema can change the value, such as a trim. On success the grid commits the schema output, not the raw input. Bulk paths commit the output too. The output type is the column value type.

This column stores the trimmed text:

import { z } from "zod";
import { defineColumns } from "@/components/data-grid/data-grid";

type Contact = { id: string; name: string };

const columns = defineColumns<Contact>()([
  {
    id: "name",
    header: "Name",
    accessorKey: "name",
    validate: z.string().trim().min(1, "Required"),
  },
]);

Report rejected cells

onValidationError fires when a write settles with a rejected cell. The writes are a paste, a fill, a Delete or Cut clear, a call of updateCells, updateRows, or editRows, and a find and replace. A rejected checkbox toggle fires it too. The grid has applied the accepted cells by then. updateCells also lists each rejected patch in its return value. Import reports its rejected cells through rejected in onImport, not here. See Control the import.

Delete and Cut validate the empty value of the cell type. A column that rejects it keeps its value, and onValidationError reports the cell with source: "delete". A validationMode: "warn" column clears the cell and flags it. Delete and Cut wait for an async schema like a paste.

PropType
source"paste" | "fill" | "stream" | "replace" | "delete" | "cut" | "edit"
rejectedGridBulkValidationError[]

These sources apply:

  • "stream" marks an updateCells or updateRows call.
  • "replace" marks a find-and-replace batch.
  • "delete" and "cut" mark a Delete or Cut clear.
  • "edit" marks a rejected checkbox toggle or an editRows call.

Each entry has rowId, columnId, viewRowIndex, value, and message. A row outside the view reports viewRowIndex: -1.

One call for a whole write

validateMany checks every cell of the column that one write sets, in one call. A 10,000-cell paste calls it once. It returns one answer per cell, in order, and null accepts. A different count rejects every cell. It runs after validate and is ignored beside a Standard Schema. A single edit calls it with one cell.

Props

PropTypeDefault
validate(value, row, ctx) => string | null or Standard Schemanone
validateMany(cells: { value, row }[]) => (string | null)[]none
validationMode"block" | "warn""block"
PropTypeDefault
onValidationError(event) => voidnone

Server mode

Validation runs in the browser in every data mode: local data, client and server pagination, scroll mode, controlled state, server sort, and server filter. validate runs before the grid emits onDataChange and onSave, so a blocking rule keeps a refused value from your server. A soft rule, a validateRow flag, skipValidation, undo or redo, and actions.commitChange let the value through. Check the same rules on your server.

A server can still refuse a value after it commits. Paint that refusal with actions.setCellErrors. It marks the cell without a data change. See Show errors on cells.

On this page