Lattice Grid

demo D89

Validation in React

Refusing a value, showing why, keeping the editor open

edit.validate

This grid refuses a bad value before it reaches the row, keeps the editor open, and shows why the value was rejected. It stops silent data corruption at the point of entry, so a user learns of a problem while they can still fix it.

Building…
Loading a live grid…

In React, a validation rule is a function on the column: edit.validate returns true to accept the typed value or a string to refuse it. The LatticeGrid component you build with createLatticeGrid takes the columns array as a prop, so Reference must look like CHG-1234, Circuits must be a whole number from 1 to 40, and Budget is capped by the circuits on the same row. The grid above holds work orders you can edit. The React code underneath is the same configuration, and the notes after it cover the event that reports a refused edit.

Install and import

npm install @toclocoinc/lattice-grid
# free on localhost; a production domain needs a licence key (see /pricing/)

import React from 'react';
import { createGrid } from '@toclocoinc/lattice-grid';
import '@toclocoinc/lattice-grid/css';
import { createLatticeGrid } from '@toclocoinc/lattice-grid/modules/react';

The configuration

<link rel="stylesheet" href="https://cdn.latticegrid.dev/lattice-grid@1.133.1/lattice-grid.min.css">

<div id="grid"></div>

<script type="module">
  import React from 'https://esm.sh/react@18';
  import { createRoot } from 'https://esm.sh/react-dom@18/client';
  import { createGrid } from 'https://cdn.latticegrid.dev/lattice-grid@1.133.1/lattice-grid.esm.min.js';
  import createLatticeGrid from 'https://cdn.latticegrid.dev/lattice-grid@1.133.1/modules/react.esm.min.js';

  const LatticeGrid = createLatticeGrid({ React, createGrid });

  // A column's validate runs on the edited value and refuses with a message the
  // cell shows. Return true to accept, a string to reject.
  const columns = [
    { field: 'id', title: 'Order', layout: { width: 120, pin: 'start' } },
    {
      field: 'reference', title: 'Reference', layout: { width: 130 },
      edit: {
        enabled: true,
        validate: ({ value }) =>
          /^(CHG|INC|REQ)-\d{4}$/.test(String(value ?? ''))
            ? true
            : 'Use CHG, INC or REQ followed by four digits.',
      },
    },
    {
      field: 'circuits', title: 'Circuits', type: 'number', layout: { width: 110 },
      edit: {
        enabled: true,
        validate: ({ value }) => {
          const n = Number(value);
          if (!Number.isInteger(n)) return 'Whole circuits only.';
          return n >= 1 && n <= 40 ? true : 'Between 1 and 40.';
        },
      },
    },
    {
      field: 'budget', title: 'Budget', type: 'number', layout: { width: 140 },
      format: { style: 'currency', currency: 'GBP' }, total: 'sum',
      edit: {
        enabled: true,
        // The row is in the bag as well as the value, so a rule can be about the
        // record rather than only about what was typed.
        validate: ({ value, row }) => {
          const n = Number(value);
          if (!Number.isFinite(n) || n < 0) return 'A budget cannot be negative.';
          const circuits = Number(row?.data?.circuits ?? 0);
          return n <= circuits * 5000
            ? true
            : `At ${circuits} circuits the cap is ${(circuits * 5000).toLocaleString('en-GB')}.`;
        },
      },
    },
  ];

  const rows = [/* work orders */];

  function App() {
    return (
      <LatticeGrid
        rowKey="id"
        selection="multiple"
        edit
        columns={columns}
        rows={rows}
        style={{ height: '540px' }}
      />
    );
  }

  createRoot(document.getElementById('grid')).render(<App />);
</script>

API notes for validation in React

  • Declaring a rule. Put edit: { enabled: true, validate } on the column. validate receives one object with value (the parsed value that was typed), oldValue, row, column, grid and context, and returns true to accept or a string to refuse. Returning nothing also accepts. The demo has three: a pattern on reference, an integer range on circuits, and a budget rule that reads row.data.circuits, so a rule can be about the record and not only the typed value. edit on the component turns editing on for the grid.
  • What the reader sees. A refused value is not written. The editor stays open on the cell and the message you returned is shown against it, so the reader can correct the value or press Escape to drop it. Nothing reaches your rows until a value passes.
  • Which event reports it. A refused commit from the cell editor ends the edit with cell:edit:end and valid: false. In React that is the onCellEditEnd prop. The event carries key, the row key, colId, the column the caret was in, and errors, a list of { colId, message }. A passing commit has valid: true and writes, the cells that were written.
  • Handling it as a callback. onCellEditEnd={(e) => { if (e.valid === false) setProblem(e.errors[0].message); }} puts the first message into your own state, for a toast or a status line. Escape also fires the event, with cancelled: true, so test valid === false rather than the absence of valid.
  • Declared rules are a second route. The grid also has declarative rules, validation: { required, min, max, pattern, oneOf, messages } on a column. Those report through the validation:failed event, which the adapter exposes as onValidationFailed, with key, failures (each with colId, code and message) and count. The demo above uses edit.validate, not those.
  • The gotcha. Keep the columns array stable, at module scope as in the code above or in useMemo. A new array is applied to the live grid with grid.setAll(), and your validators are part of what it applies, so a new array on every render is applied every time. Do not throw inside validate: a throw is reported once and the edit is rejected.

How do I show a validation message from a React grid in my own UI?

Pass onCellEditEnd and read e.errors when e.valid === false. Each entry has the colId and the message your validate returned, so you can store it in state and render it outside the grid. The grid still shows the message against the cell.

Can a React validator compare against another column in the same row?

Yes. The object validate receives includes row, and row.data is the record, so the budget rule in the demo reads row.data.circuits to set its cap. It sees the row as it stands before the edit is written.

What is the difference between edit.validate and validation:failed in React?

edit.validate is a function on the column that you write, and a refusal arrives as onCellEditEnd with valid: false. The declarative validation key holds named rules such as min and oneOf with per-rule messages, and arrives as onValidationFailed with a code per failure. Use whichever fits; the demo uses the function form.

Rejecting a bad value without closing the editor

Validation stops a commit before a bad value reaches the row: the editor stays open, the cell carries an error state, and the user sees why the value was refused rather than finding out later that a save silently dropped a field. A developer reaches for this on any column where the underlying type or a business rule is narrower than free text accepts: a quantity that cannot go negative, a date that cannot precede an order date in the same row, a code that must match a fixed list. Lattice Grid wires this through edit.validate, a per-column function that receives the pending value and the row and returns either nothing or a message; a message blocks the commit and keeps focus in the editor instead of letting Tab or Enter move on. Validation runs against the row already resolved for that cell, so a rule checking one field against a sibling field costs a single comparison, not a rescan of the grid. The error message is attached to the input through aria-describedby for the duration of the failure, so a screen reader reads the reason with the value rather than through a separate alert. This keeps a JavaScript data grid’s inline editing honest without a modal or a confirmation step breaking the flow of entering data.

How do I stop an invalid value from being saved in a grid cell?

Set edit.validate on the column to a function that inspects the pending value and the row, returning an error message when the value should be refused. While that message is present, the commit on Tab, Enter, or clicking away is blocked, the editor stays open, and the message is exposed to assistive technology alongside the cell so the reason is announced with the failure.