gridcn2.0.0
Validation examples

Cross-field validation example

Flag a cell with a row rule that compares two columns, judged once after a whole edit, paste, or fill commits.

A validate rule sees one cell. A rule that spans two columns needs the whole row. In this grid, End must stay at or after Start. Make an End earlier than its Start by editing one cell or by pasting both. The End cell gets the row message, and the value still commits. Make the row consistent again and the flag clears.

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
pnpm dlx shadcn@latest add @gridcn/data-grid-cross-field-demo

The rule

validateRow runs once for each touched row after a write gesture commits. The row it receives holds every cell of the gesture, so the rule judges a pasted block of Start and End pairs as one state:

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

type Task = { id: string; task: string; start: number; end: number };

const columns = defineColumns<Task>()([
  { id: "task", header: "Task", accessorKey: "task" },
  { id: "start", header: "Start", accessorKey: "start", type: "number" },
  { id: "end", header: "End", accessorKey: "end", type: "number" },
]);

export function Tasks({ tasks }: { tasks: Task[] }) {
  return (
    <DataGrid
      defaultData={tasks}
      columns={columns}
      getRowId={(row) => row.id}
      validateRow={(row) =>
        row.end < row.start ? { end: "End must be at or after Start" } : null
      }
    />
  );
}
  • Return an object of columnId to message to flag cells. Return null when the row is fine.
  • A flag uses the display of a server error: ring, tint, tooltip, and aria-invalid.
  • The value still commits. A later write that makes the row consistent clears the flag, also when it writes a different column than the flagged one.
  • validateRow does not run on insertRows, duplicateRows, or a row delete. It does not run after you replace the data array. It runs for the rows that actions.commitChange inserts, such as an import, an undo, or a rollback.
  • validateRow can return a promise. See Async gates example.

On this page