Lattice Grid

demo D89

Validation in Angular

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 Angular, 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 standalone LatticeGridComponent from @toclocoinc/lattice-grid/angular takes the whole configuration through its config input, 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 Angular code underneath is the same configuration, and the notes after it cover the output 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 { createGrid } from '@toclocoinc/lattice-grid';
import '@toclocoinc/lattice-grid/css';
import { LatticeGridComponent, provideLattice } from '@toclocoinc/lattice-grid/angular';

The configuration

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { createGrid } from '@toclocoinc/lattice-grid';
import '@toclocoinc/lattice-grid/css';
import { LatticeGridComponent, provideLattice } from '@toclocoinc/lattice-grid/angular';

// 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 */];



@Component({
  selector: 'app-root',
  standalone: true,
  imports: [LatticeGridComponent],
  template: '<lattice-grid [config]="grid" style="display:block;height:540px"></lattice-grid>',
})
export class AppComponent {
  grid = {
    rowKey: 'id',
    selection: 'multiple',
    edit: true,
    columns: columns,
    rows: rows,
  };
}

bootstrapApplication(AppComponent, {
  providers: [provideLattice({ createGrid })],
});

API notes for validation in Angular

  • Declaring a rule. Put edit: { enabled: true, validate } on the column, inside the columns of the config input. 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: true in the config 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 output reports it. A refused commit from the cell editor ends the edit with the cell:edit:end event and valid: false. In Angular that is the (cell-edit-end) output. 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.
  • Handling it as an output. Bind it on the element, (cell-edit-end)="onEditEnd($event)", and in the method test if (e.valid === false) this.problem.set(e.errors[0].message);. The grid runs outside the zone, and a bound output re-enters it, so a signal or a template binding updates without further work. 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 arrives as (validation-failed), with key, failures (each with colId, code and message) and count. The demo above uses edit.validate, not those.
  • The gotcha. The [config] input is compared by identity and never rebuilds the grid, so hold the configuration in a field, as the code above does with grid, and the validators in it stay put. Do not throw inside validate: a throw is reported once and the edit is rejected.

How do I show a validation message from an Angular grid in my own template?

Bind (cell-edit-end) and read e.errors when e.valid === false. Each entry has the colId and the message your validate returned, so you can keep it in a signal and render it outside the grid. The grid still shows the message against the cell.

Can an Angular 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 Angular?

edit.validate is a function on the column that you write, and a refusal arrives on (cell-edit-end) with valid: false. The declarative validation key holds named rules such as min and oneOf with per-rule messages, and arrives on (validation-failed) 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.