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.
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
columnIdto message to flag cells. Returnnullwhen 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.
validateRowdoes not run oninsertRows,duplicateRows, or a row delete. It does not run after you replace thedataarray. It runs for the rows thatactions.commitChangeinserts, such as an import, an undo, or a rollback.validateRowcan return a promise. See Async gates example.
Related
- Cross-field rules: the full contract
- Server errors example: the display that
validateRowreuses