# Editable grid with validation and undo

> Validate user input with valueParser and editable callbacks, show feedback, and let users undo and redo edits with undoRedo, api.undo() and api.redo().

A data-entry grid needs three things: rules about which cells can change, checks on what users type, and a way back from mistakes. Birch UI Grid covers all three in the free package.

**Live demo: Validation with undo and redo** (runs on the HTML version of this page). Source of `demos/recipe-grid-undo-validation.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { button, docsTheme, layout, makeOrders, onDocsThemeChange, type Order } from './_shared';

export const meta = { title: 'Validation with undo and redo', height: 440 };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const report = (message: string) => {
    status.textContent = message;
  };

  const columns: ColumnDef<Order>[] = [
    { field: 'id', header: 'Order', width: 110 },
    { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, editable: true },
    {
      field: 'quantity',
      header: 'Qty',
      type: 'number',
      width: 90,
      editable: true,
      editor: 'number',
      valueParser: (input, order) => {
        const quantity = Number(input);
        if (Number.isInteger(quantity) && quantity >= 1 && quantity <= 500) return quantity;
        report(`${order.id}: quantity must be a whole number from 1 to 500. Kept ${order.quantity}.`);
        return order.quantity;
      },
    },
    {
      field: 'discount',
      header: 'Discount',
      type: 'number',
      width: 110,
      editable: true,
      format: (value) => `${Math.round(Number(value) * 100)}%`,
      valueParser: (input, order) => {
        const percent = Number(String(input).replace('%', ''));
        if (Number.isFinite(percent) && percent >= 0 && percent <= 30) return percent / 100;
        report(`${order.id}: discount must be between 0% and 30%. Kept ${Math.round(order.discount * 100)}%.`);
        return order.discount;
      },
    },
    {
      field: 'status',
      header: 'Status',
      width: 130,
      editable: (ctx) => ctx.row?.status !== 'Returned',
      editor: 'select',
      options: ['Pending', 'Shipped', 'Delivered', 'Returned'],
    },
  ];

  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(120, 21),
    getRowId: (order) => order.id,
    undoRedo: { limit: 50 },
    theme: docsTheme(),
    ariaLabel: 'Editable orders with undo',
  });

  const undoButton = button('Undo', () => grid.undo());
  const redoButton = button('Redo', () => grid.redo());
  const sync = () => {
    undoButton.disabled = !grid.canUndo();
    redoButton.disabled = !grid.canRedo();
  };
  sync();
  toolbar.append(undoButton, redoButton, 'Ctrl+Z undoes, Ctrl+Y or Ctrl+Shift+Z redoes.');
  report('Try a quantity of 0 or a discount of 45%.');

  const offChange = grid.on('cellValueChanged', ({ row, colId, newValue, source }) => {
    sync();
    report(`${row.id}: ${colId} set to ${String(newValue)} (${source}).`);
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    offChange();
    stopTheme();
    grid.destroy();
  };
}
```

## 1. Lock cells that must not change

`editable` accepts a function of the cell context, so rules can depend on the row:

```ts
{
  field: 'status',
  header: 'Status',
  editor: 'select',
  options: ['Pending', 'Shipped', 'Delivered', 'Returned'],
  editable: (ctx) => ctx.row?.status !== 'Returned',
}
```

## 2. Validate input in `valueParser`

`valueParser(input, row)` receives the raw text from the editor and returns the value to store. To reject input, return the current value: the cell does not change and no `cellValueChanged` fires.

```ts title="order-columns.ts"
import type { ColumnDef } from '@birchui/core';
import type { OrderLine } from './orders';
import { showFieldError } from './feedback';

export const columns: ColumnDef<OrderLine>[] = [
  { field: 'sku', header: 'SKU', width: 120 },
  { field: 'product', header: 'Product', flex: 1, editable: true },
  {
    field: 'quantity',
    header: 'Qty',
    type: 'number',
    editor: 'number',
    editable: true,
    valueParser: (input, line) => {
      const quantity = Number(input);
      if (Number.isInteger(quantity) && quantity >= 1 && quantity <= 500) return quantity;
      showFieldError(`${line.sku}: quantity must be a whole number from 1 to 500`);
      return line.quantity;
    },
  },
  {
    field: 'discount',
    header: 'Discount',
    type: 'number',
    editable: true,
    format: (value) => `${Math.round(Number(value) * 100)}%`,
    valueParser: (input, line) => {
      const percent = Number(input.replace('%', ''));
      if (Number.isFinite(percent) && percent >= 0 && percent <= 30) return percent / 100;
      showFieldError(`${line.sku}: discount must be between 0% and 30%`);
      return line.discount;
    },
  },
];
```

For rules that involve several fields, or a value that arrives through `setValue()`, validate in `valueSetter` instead. A `valueSetter` that throws keeps the old value and fires no `cellValueChanged`, but the error is reported with `console.error`, so prefer `valueParser` for ordinary user mistakes.

## 3. Turn on undo and redo

```ts title="order-lines-grid.ts"
import { createGrid } from '@birchui/core';
import { columns } from './order-columns';

const grid = createGrid(document.querySelector<HTMLElement>('#lines')!, {
  columns,
  rows: lines,
  getRowId: (line) => line.sku,
  undoRedo: { limit: 50 },
});

const undoButton = document.querySelector<HTMLButtonElement>('#undo')!;
const redoButton = document.querySelector<HTMLButtonElement>('#redo')!;

const syncButtons = () => {
  undoButton.disabled = !grid.canUndo();
  redoButton.disabled = !grid.canRedo();
};

undoButton.addEventListener('click', () => grid.undo());
redoButton.addEventListener('click', () => grid.redo());
grid.on('cellValueChanged', syncButtons);
syncButtons();
```

`undoRedo: true` keeps the last 100 steps; pass `{ limit }` to change that. With focus in the grid, <kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes (<kbd>Cmd</kbd> on macOS).

**`UndoRedoOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface UndoRedoOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `limit?` | `number` |  |

## 4. Save changes, including undos

Undo and redo write values back through the normal path, so `cellValueChanged` fires with `source: 'undo'` or `'redo'`. A save handler that listens to the event therefore persists undos too:

```ts
grid.on('cellValueChanged', async ({ row, colId, oldValue, newValue, source }) => {
  try {
    await fetch(`/api/order-lines/${row.sku}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ [colId]: newValue }),
    });
  } catch {
    if (source !== 'undo') grid.setValue(row, colId, oldValue);
  }
});
```

## How it works

- Every value change is recorded: edits, `setValue()` calls, paste and fill handle changes. Changes made in the same task form one step, so undoing a paste of 200 cells restores all of them at once.
- Undo stops an edit in progress, scrolls to the first restored cell and announces the result to screen readers.
- A new change after an undo clears the redo stack.
- `clearHistory()` empties both stacks, for example after a successful bulk save. Setting `undoRedo: false` with `update()` clears them as well.
- The keyboard shortcuts are ignored while a cell editor or any other text input has focus, so the browser's own undo works inside the editor.

## Pitfalls

- **Set `getRowId`.** History stores row ids; without stable ids an undo after a sort or a `setRows()` can target the wrong row.
- **`setRows()` does not clear history.** If you load a different data set, call `clearHistory()`.
- **Undo is per grid.** Two grids on one page keep separate stacks.

## Related

- [Editing](https://docs.birchui.com/grid/editing.md), especially [Parsing input: valueParser](https://docs.birchui.com/grid/editing.md#parsing-input-valueparser) and [Validation and rollback](https://docs.birchui.com/grid/editing.md#validation-and-rollback).
- [Keyboard-only workflows](https://docs.birchui.com/recipes/grid-keyboard-workflows.md).
- [`cellValueChanged`](https://docs.birchui.com/grid/events.md#cellvaluechanged).
