Cell validator
Cell validators run whenever a cell’s value changes, whether a user edits, pastes, or autofills it, or your code writes it. Use them to enforce data rules such as required fields, numeric ranges, or pattern matching.
Overview
When you create a validator, assign it an alias so you can reference it by name in column configuration. Handsontable DataGrid defines 10 aliases by default:
autocompleteforHandsontable.validators.AutocompleteValidatorcheckboxforHandsontable.validators.CheckboxValidatordateforHandsontable.validators.DateValidatordropdownforHandsontable.validators.DropdownValidatorintl-datefor theintlDateValidatorfunctionintl-datetimefor theintlDatetimeValidatorfunctionintl-timefor theintlTimeValidatorfunctionmultiselectforHandsontable.validators.MultiselectValidatornumericforHandsontable.validators.NumericValidatortimeforHandsontable.validators.TimeValidator
Aliases give you a convenient way to specify which validator runs when table validation triggers. You don’t need to reference the validator function directly, and you can swap the function behind an alias without changing your column configuration.
Invalid cell commit semantics vs. visual marking
When a validator returns false, Handsontable independently controls two separate outcomes:
- Commit behavior — controlled by
allowInvalid. Whentrue(the default), the invalid value is written to the data source and the editor closes. Whenfalse, the editor stays open and the value is rejected until the user enters something that passes validation. - Visual marking — controlled by
invalidCellClassName. Regardless of [allowInvalid], Handsontable applies a CSS class to every cell whose validator returnedfalse. The default class is htInvalid; you can replace it per-column or table-wide using [invalidCellClassName].
The following snippet shows both options used together on a single column:
These two options work independently. You can configure [allowInvalid] and [invalidCellClassName] together without one affecting the other.
columns: [ { data: 'ip', validator: ipValidatorRegexp, allowInvalid: true, invalidCellClassName: 'my-invalid-cell' }]When validation runs
Handsontable validates a cell every time its value changes through the grid. It doesn’t matter what made the change. Validation runs for each of these operations:
| Operation | source in afterChange |
|---|---|
| Typing in a cell and confirming the edit | edit |
| Pressing Delete or Backspace on selected cells | edit |
| Filling a selection with Ctrl/⌘+Enter | edit |
| Pasting | CopyPaste.paste |
| Cutting | CopyPaste.cut |
| Dragging or double-clicking the fill handle | Autofill.fill |
| Selecting Clear column in the context menu | ContextMenu.clearColumn |
| Undoing or redoing a change | UndoRedo.undo, UndoRedo.redo |
Calling setDataAtCell() or setDataAtRowProp() | edit, or the source you pass |
Calling populateFromArray() | populateFromArray, or the source you pass |
Undo and redo validate the cells they restore again, so a restored value gets the same valid or invalid state it had before.
These operations don’t run validators:
- Loading data with the
dataoption,loadData(), orupdateData(). - Writing source data with
setSourceDataAtCell(). - Inserting or removing rows and columns.
To validate data you loaded, call validateCells(), validateRows(), or validateColumns().
If a validator seems not to run
Check these settings first:
allowInvalid— With the defaulttrue, Handsontable saves an invalid value and only marks the cell with thehtInvalidclass. The change isn’t rejected. SetallowInvalidtofalseto reject invalid values.- Type conversion — A
numericcell converts the string'12'to the number12before your validator runs. A validator that checks for a string never matches. - Asynchronous validators — Your validator must call
callback(true)orcallback(false)on every code path. If it never calls the callback, Handsontable never saves the change, andafterChangedoesn’t fire. beforeValidatereturn values — AbeforeValidatelistener that returns a value replaces the value your validator receives. To only observe validation, don’t return anything from the listener.
Limit the text length without a validator
To limit the number of characters in a cell, set the maxLength option. You don’t need to write a validator. Handsontable validates the length for you, and the text cell editor stops the user from typing more characters than the limit allows.
maxLength counts the characters a reader sees, so a flag or an emoji with a skin tone counts as one character. A value that is too long is invalid. Like any other invalid value, allowInvalid decides whether the grid keeps it, and invalidCellClassName sets the class that marks the cell.
If a cell has both maxLength and a validator, the value must pass both checks. Handsontable checks the length first, and doesn’t call your validator for a value that is too long.
For a full description and examples, see Limiting the text length in the text cell type guide.
Register custom cell validator
To register your own alias use Handsontable.validators.registerValidator() function. It takes two arguments:
validatorName- a string representing a validator functionvalidator- a validator function that will be represented byvalidatorName
If you’d like to register creditCardValidator under alias credit-card you have to call:
Handsontable.validators.registerValidator('credit-card', creditCardValidator);Choose aliases wisely. If you register your validator under name that is already registered, the target function will be overwritten:
Handsontable.validators.registerValidator('date', creditCardValidator);Now ‘date’ alias points to creditCardValidator function, not Handsontable.validators.DateValidator.
So, unless you intentionally want to overwrite an existing alias, try to choose a unique name. A good practice is prefixing your aliases with some custom name (for example your GitHub username) to minimize the possibility of name collisions. This is especially important if you want to publish your validator, because you never know aliases has been registered by the user who uses your validator.
Handsontable.validators.registerValidator('credit-card', creditCardValidator);Someone might already registered such alias.
Handsontable.validators.registerValidator('my.credit-card', creditCardValidator);That’s better.
Using an alias
The final touch is to use the registered aliases, so that you can easily refer to them without knowing the actual validator function.
To sum up, a well prepared validator function should look like this:
(Handsontable => { function customValidator(query, callback) { // ...your custom logic of the validator
callback(/* Pass `true` or `false` based on your logic */); }
// Register an alias Handsontable.validators.registerValidator('my.custom', customValidator);
})(Handsontable);From now on, you can use customValidator like so:
<hot-table [settings]="{ columns: [{ validator: 'my.custom' }] }"></hot-table>Validate decimal numbers with dot or comma separators
Use a custom validator when a column must accept decimal values with either . or , as the decimal separator. The following example validates campaign conversion rates. It accepts values such as 3.4 and 8,1, and rejects values that do not match the decimal format.
/* file: app.component.ts */import { Component } from '@angular/core';import { GridSettings, HotTableModule } from '@handsontable/angular-wrapper';
const data = [ ['Spring Sale 2025', 'Email', '3.4'], ['Brand Awareness Q3', 'Paid Search', '8,1'], ['Retention Push', 'In-app', '12.0'], ['Partner Webinar', 'Organic', '6,75'], ['Holiday Preview', 'Social', '9.25'],];
type CellMeta = { allowEmpty?: boolean };
function decimalValidator(this: CellMeta, value: unknown, callback: (valid: boolean) => void) { if (this.allowEmpty && (value === null || value === undefined || value === '')) { callback(true);
return; }
callback(/^\d+[.,]\d+$/.test(String(value)));}
@Component({ selector: 'example2-cell-validator', standalone: true, imports: [HotTableModule], template: ` <hot-table [data]="data" [settings]="gridSettings"></hot-table> `,})export class AppComponent { readonly data = data;
readonly gridSettings: GridSettings = { colHeaders: ['Campaign', 'Channel', 'Conversion rate'], columns: [ {}, {}, { validator: decimalValidator, allowInvalid: false, }, ], height: 'auto', autoWrapRow: true, autoWrapCol: true, };}/* end-file */
/* file: app.config.ts */import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';import { registerAllModules } from 'handsontable/registry';import { HOT_GLOBAL_CONFIG, HotGlobalConfig } from '@handsontable/angular-wrapper';
// register Handsontable's modulesregisterAllModules();
export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), { provide: HOT_GLOBAL_CONFIG, useValue: { // license: 'your-license-key', // get a key at https://handsontable.com/pricing/ } as HotGlobalConfig, }, ],};/* end-file */<div> <example2-cell-validator></example2-cell-validator></div>Full featured example
Use the validator method to easily validate synchronous or asynchronous changes to a cell. If you need more control, beforeValidate and afterValidate hooks are available. In the below example, email_validator_fn is an async validator that resolves after 1000 ms.
Use the allowInvalid option to define if the grid should accept input that does not validate. If you need to modify the input (e.g., censor bad words, uppercase first letter), use the plugin hook beforeChange.
By default, all invalid cells are marked by the htInvalid CSS class. If you want to use a different class name, set invalidCellClassName — this replaces htInvalid for the affected cells. Add a CSS rule in your stylesheet for the chosen class. To apply a custom class name, add the invalidCellClassName option to your Handsontable settings. For example:
For the entire table
invalidCellClassName: 'myInvalidClass'For specific columns
columns: [ { data: 'firstName', invalidCellClassName: 'myInvalidClass' }, { data: 'lastName', invalidCellClassName: 'myInvalidSecondClass' }, { data: 'address' }]Callback console log:
/* file: app.component.ts */import { Component, OnInit } from '@angular/core';import { GridSettings, HotTableModule} from '@handsontable/angular-wrapper';import type Handsontable from 'handsontable/base';
const ipValidatorRegexp = /^(?:\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b|null)$/;
const emailValidator = (value: unknown, callback: (valid: boolean) => void) => { setTimeout(() => { if (/.+@.+/.test(String(value))) { callback(true); } else { callback(false); } }, 1000);};
@Component({ selector: 'app-example1', template: ` <output class="console">{{output}}</output>
<hot-table [settings]="hotSettings!" [data]="hotData"> </hot-table> `, standalone: true, imports: [HotTableModule],})export class AppComponent implements OnInit { output = 'Here you will see the log';66 collapsed lines
readonly hotData = [ { id: 1, name: { first: 'Joe', last: 'Fabiano' }, ip: '0.0.0.1', email: 'Joe.Fabiano@ex.com', }, { id: 2, name: { first: 'Fred', last: 'Wecler' }, ip: '0.0.0.1', email: 'Fred.Wecler@ex.com', }, { id: 3, name: { first: 'Steve', last: 'Wilson' }, ip: '0.0.0.1', email: 'Steve.Wilson@ex.com', }, { id: 4, name: { first: 'Maria', last: 'Fernandez' }, ip: '0.0.0.1', email: 'M.Fernandez@ex.com', }, { id: 5, name: { first: 'Pierre', last: 'Barbault' }, ip: '0.0.0.1', email: 'Pierre.Barbault@ex.com', }, { id: 6, name: { first: 'Nancy', last: 'Moore' }, ip: '0.0.0.1', email: 'Nancy.Moore@ex.com', }, { id: 7, name: { first: 'Barbara', last: 'MacDonald' }, ip: '0.0.0.1', email: 'B.MacDonald@ex.com', }, { id: 8, name: { first: 'Wilma', last: 'Williams' }, ip: '0.0.0.1', email: 'Wilma.Williams@ex.com', }, { id: 9, name: { first: 'Sasha', last: 'Silver' }, ip: '0.0.0.1', email: 'Sasha.Silver@ex.com', }, { id: 10, name: { first: 'Don', last: 'Pérignon' }, ip: '0.0.0.1', email: 'Don.Pérignon@ex.com', }, { id: 11, name: { first: 'Aaron', last: 'Kinley' }, ip: '0.0.0.1', email: 'Aaron.Kinley@ex.com', }, ];
hotSettings!: GridSettings;
ngOnInit() { const componentInstance = this;
this.hotSettings = { beforeChange(changes: (Handsontable.CellChange | null)[]) { for (let i = changes.length - 1; i >= 0; i--) { const currChange = changes[i];
if (!currChange) { continue; }
// gently don't accept the word "foo" (remove the change at index i) if (currChange[3] === 'foo') { changes.splice(i, 1); } // if any of pasted cells contains the word "nuke", reject the whole paste else if (currChange[3] === 'nuke') { return false; } // capitalise first letter in column 1 and 2 else if ( currChange[1] === 'name.first' || currChange[1] === 'name.last' ) { if (currChange[3] !== null && typeof currChange[3] === 'string') { changes[i]![3] = currChange[3].charAt(0).toUpperCase() + currChange[3].slice(1); } } }
return true; }, afterChange(changes: Handsontable.AppliedCellChange[] | null, source: Handsontable.ChangeSource) { if (source !== 'loadData') { componentInstance.output = JSON.stringify(changes); } }, colHeaders: ['ID', 'First name', 'Last name', 'IP', 'E-mail'], height: 'auto', // licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/ columns: [ { data: 'id', type: 'numeric' }, { data: 'name.first' }, { data: 'name.last' }, { data: 'ip', validator: ipValidatorRegexp, allowInvalid: true }, { data: 'email', validator: emailValidator }, ], autoWrapRow: true, autoWrapCol: true, }; }}/* end-file */
/* file: app.config.ts */import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';import { registerAllModules } from 'handsontable/registry';import { HOT_GLOBAL_CONFIG, HotGlobalConfig } from '@handsontable/angular-wrapper';
// register Handsontable's modulesregisterAllModules();
export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), { provide: HOT_GLOBAL_CONFIG, useValue: { // license: 'your-license-key', // get a key at https://handsontable.com/pricing/ } as HotGlobalConfig, }, ],};/* end-file */<div> <app-example1></app-example1></div>Edit the above grid to see the changes argument from the callback.
Mind that changes in table are applied after running all validators (both synchronous and and asynchronous) from every changed cell.
When you write to the same cell twice while an asynchronous validator is still running, the last write wins. If the validator of the newer write answers first, Handsontable applies the newer value and drops the older one, and the cell keeps the validity of the newer value. The dropped write fires beforeChange but not afterChange. If the newer write is rejected because allowInvalid is false, the older write still applies.
The order holds only among writes that wait on a validator. A setSourceDataAtCell() call is not tracked, and neither is a correction that a validator writes late with a setDataAtCell() source ending in Validator, so an older validated write can still land on top of either.
If you call loadData() while a cell’s validator hasn’t answered yet, Handsontable drops the write: the new data doesn’t get the value. This applies to every validator, including a synchronous one, a cell type’s own validator (such as numeric or date), and maxLength, because Handsontable always runs validators after the call that made the change returns. So setDataAtCell() followed by loadData() in the same function drops the value too. The dropped write fires beforeChange and the validation hooks, but not afterChange, and the row and column the validation hooks report refer to the data before the load. An editor that waits for that validator closes without saving.
updateData() doesn’t drop the write, because it’s meant for the same records in a new array. If the new array holds other records, the value is written into the record at the same row and column. To replace the records and drop the write, use loadData().
Validators and formulas
With the Formulas plugin, a cell that can reject a change (it has a validator and allowInvalid: false) reaches HyperFormula only after validation. Until then, formulas that depend on the cell keep their old values, so a rejected value never shows through them. A validator of another cell that reads such a dependent formula while it waits gets the result from before the change.
The validator of a formula cell gets the formula’s result, not its text. When a change writes a formula that reads another changed cell, the validator gets the result for that cell’s new value. If a validation rejects that other cell, the formula is validated again with the result for the other cell’s old value. This needs your engine’s undoLimit to be 2 or more, and its evaluation not to be suspended. Otherwise, the validator gets the result for the other cell’s old value first, and the formula is validated again when the change is applied. A validator that answers in its own call keeps what it writes in the edit’s undo step in that case. A validator that answers later does not.
FAQ: Does the invalid CSS class still apply when allowInvalid is true?
Yes. When allowInvalid is and a validator returns false, the value is written to the data source (the editor closes normally), but Handsontable still applies the invalid CSS class to the cell. By default that class is htInvalid; you can change it per-column or globally with the invalidCellClassName option. The two concerns — whether to accept the value and how to mark the cell — are fully independent. See also the allowInvalid option for details.
Result
You now have a cell validator that enforces data rules when a user finishes editing. Register it under an alias to reference it by name across your column configuration. Use allowInvalid set to false to keep the editor open until the user enters a valid value, or allowInvalid set to true to accept the value while still visually flagging the cell. Use invalidCellClassName to customize the CSS class applied to cells that fail validation — the default is htInvalid.
Related API reference
APIs
Configuration options
Core methods
Hooks