gridcn2.0.0
Editing cells

Row validation and async checks

Check fields against each other with validateRow or a schema refine, and wait for an async schema on every write path.

A column's validate sees one value. This page covers two checks that go beyond it. validateRow compares the fields of a row. An async schema waits for a remote answer. Live grids are in the cross-field example and the async example.

Make an End time earlier than its Start (edit one cell, or paste both): the End cell gets flagged with the row-level message and the value still commits. Set the row consistent again and the flag clears.

Task
Start
End
Silent Tiger
9
17
Quick Lion
9
17
Swift Wolf
9
17
Eager Lion
9
17
Eager Tiger
9
17
Silent Wolf
9
17
Swift Lion
9
17
Eager Lion
9
17

Before you start, set up column rules as Validation describes. Check the same rules on your server, because validation runs in the browser only.

Check fields against each other

validateRow checks a row after a write gesture commits: an edit, a paste, a fill, a clear, updateCells, or updateRows. It runs once per touched row, with all cells of the gesture applied, so the verdict never depends on column order.

To flag cells, return a columnId to message map. If the row is fine, return null. The flags use the same display as server errors: ring, tint, tooltip, and aria-invalid. The values still commit. Any later write that makes the row consistent clears the flags, whichever column it writes.

This grid flags a discount above the price:

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

type Line = { id: string; price: number; discount: number };

const columns = defineColumns<Line>()([
  { id: "price", header: "Price", accessorKey: "price", type: "number" },
  {
    id: "discount",
    header: "Discount",
    accessorKey: "discount",
    type: "number",
  },
]);

const checkLine = (row: Line) =>
  row.discount > row.price ? { discount: "Discount above price" } : null;

export function Lines({ lines }: { lines: Line[] }) {
  return (
    <DataGrid defaultData={lines} columns={columns} validateRow={checkLine} />
  );
}

validateRow does not run on a row insert or duplicate, because a fresh default row is incomplete. It does not run on a row delete, or after you replace the data array.

validateRow runs on more paths:

  • actions.commitChange inserts or updates rows, for every change source except "stream".
  • An import replaces the data with delete and insert operations. The grid validates each imported row, and not the deleted rows.
  • An undo, a redo, or a rollback restores rows. A cross-field error that the undone edit caused goes away.

A newer change that touches the row cancels its pending verdict.

validateRow can return a promise. The write commits first. The verdict merges after the promise settles. A newer verdict for the same row replaces a pending one. The grid drops a verdict for a row that is gone. A rejected promise or a thrown error adds no error and keeps the write.

validateRow receives { signal } as its third argument. The signal aborts when a newer verdict replaces this one, the row is gone, gateTimeoutMs runs out, or the grid unmounts. The grid drops an aborted verdict.

Schema refine rules

A column schema receives only the cell value, so its refine checks one value. Put a rule that compares fields in validateRow. To use an object schema, parse the row and map each issue to its column:

import { z } from "zod";

const LineSchema = z
  .object({ price: z.number(), discount: z.number() })
  .refine((line) => line.discount <= line.price, {
    path: ["discount"],
    message: "Discount above price",
  });

export function validateLine(row: unknown) {
  const { success, error } = LineSchema.safeParse(row);
  if (success) return null;
  return Object.fromEntries(
    error.issues.map((issue) => [issue.path.join("."), issue.message]),
  );
}

Pass validateRow={validateLine}. For an async refine, return the promise of safeParseAsync.

Check for duplicate values

A column validate sees one value, so it cannot tell whether another row holds it. unique() is a validate function that does. In a paste or a fill, the row of a column validate is the row as it was before the gesture. unique() also reads the other cells of the gesture:

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

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

const columns = defineColumns<Account>()([
  {
    id: "email",
    header: "Email",
    accessorKey: "email",
    validate: unique({ message: "Email is taken", ignoreCase: true }),
  },
]);

export function Accounts({ accounts }: { accounts: Account[] }) {
  return <DataGrid defaultData={accounts} columns={columns} />;
}

unique() compares the value with the other rows and with the other cells of the same paste or fill. Blank values pass. An import compares with the grid rows on the default append, and with existingRows in buildImportedRows. A chunked import of more than 5,000 rows compares each chunk on its own. unique() takes message (default "Must be unique") and ignoreCase (default false).

Server mode

validateRow runs in the browser in every data mode. unique() sees the loaded rows only, so check uniqueness on the server too.

Wait for an async schema

A Standard Schema can return a promise, for example for a uniqueness check. The function form is synchronous. The same column definition covers a single edit and every bulk path:

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

async function isSkuFree(sku: string) {
  const res = await fetch(`/api/sku/${encodeURIComponent(sku)}`);
  return res.ok;
}

type Item = { id: string; sku: string };

const columns = defineColumns<Item>()([
  {
    id: "sku",
    header: "SKU",
    accessorKey: "sku",
    validate: z.string().refine(isSkuFree, "Already in use"),
  },
]);

In a single-cell edit, the editor stays open while the schema resolves. The built-in text and number inputs turn readOnly, never disabled, so Escape still cancels. If the schema resolves with issues, the message shows like a sync rejection and editing continues. If it succeeds, the grid commits result.value and then applies the pending move from Enter, unless the user selected another cell in the meantime.

Escape, a newer commit, an unmounted cell, or a restarted edit on the same cell invalidates the pending check. The grid drops its result silently.

On bulk paths

Paste, fill, and updateCells hold the batch while an async schema resolves:

  • The grid runs at most 32 validations at once. A paste of 10,000 cells makes 32 calls at a time.
  • Nothing changes until every verdict is in. The accepted cells then commit together as one change.
  • A rejected cell drops and the other cells still commit.
  • A second paste, a sort or filter change, a deleted target row, or an unmounted grid drops the held batch silently. Paste and fill each supersede only their own batch. Other writes also drop a held updateCells batch. Stream updates lists them.

Import validates each cell the same way. It writes an empty value for a rejected cell. See Import.

A slow schema makes a slow batch

For a large paste against a remote check, validate the block once with processPaste of Clipboard. A 200 ms call across 10,000 cells takes about 60 seconds, and the grid shows no progress. processPaste does not cover a fill, and gateTimeoutMs aborts a slow fill like any async validate. A large fill against a remote check runs one call for each cell.

actions.updateCells(patches, { skipValidation: true }) skips validate for a trusted feed.

Props

PropTypeDefault
validateRow(row, rowId, { signal }) => Record<string, string> | null or a promise of itnone

On this page