ValidationMIT
Built-in validation rules, expression and asynchronous custom validators, when validation runs, how errors are shown, and how to check a schema itself.
Birch UI Forms validates as the user works, shows each message next to its field, and on submit lists every problem in an error summary with links to the fields. Built-in rules come from the field properties you already set; for anything else there are expression validators and asynchronous custom validators.
Built-in rules#
| Rule | Applies to | Message (English) |
|---|---|---|
required |
All fields. Checkbox and toggle must be on; a matrix needs every row answered; a repeating section needs at least one entry. | This field is required. |
requiredIf |
Same as required, while the expression is true. |
This field is required. |
| Email format | email |
Enter a valid email address, like [email protected]. |
Number, integer |
number, slider |
Enter a number. / Enter a whole number. |
min, max |
number, slider |
Enter a value of at least {min}. / no more than {max}. |
minLength, maxLength |
text, email, textarea |
Enter at least {min} characters. / no more than {max}. |
pattern |
text |
patternMessage, or "Enter a value in the expected format." |
Valid date or time, min, max |
date, time, datetime |
This value is not valid. / Enter a date on or after {min}. |
minSelected, maxSelected |
multiselect, checkboxgroup |
Select at least {min} options. / no more than {max}. |
accept, maxSize, maxFiles |
file |
{file} is not an accepted file type. / {file} is larger than {max}. / Attach no more than {max} files. |
minPanels, maxPanels |
dynamicpanel |
Add at least {min} entries. / no more than {max}. |
Rules other than required only run on a field that has a value, so an optional field can be left empty. pattern must match the whole value, and an invalid pattern is ignored rather than blocking the user. Date messages show dates in the form's locale, for example "Enter a date on or after 1 Dec 2026." in en-GB.
Change any message per field with requiredMessage or patternMessage, or for the whole form with the messages option or a locale.
Expression validators#
An expression validator is a rule written as an expression that must be true for the value to be accepted. It can compare fields, use dates relative to today and call functions.
{
type: 'date',
name: 'returnBy',
title: 'Return by',
required: true,
validators: [
{ type: 'expression', expression: '{returnBy} >= {collectOn}', message: 'Return the equipment after you collect it.' },
{
type: 'expression',
expression: "dateDiff({collectOn}, {returnBy}, 'days') <= 14",
message: 'Equipment can be borrowed for up to 14 days.',
},
],
}Validators run in order and the first failing one sets the message; without a message, the form shows "This value is not valid." Like the built-in rules, they only run when the field has a value. An expression that cannot be evaluated is reported through formError and does not block the user.
Custom validators#
For checks that need your code or your server, such as "is this email already registered" or "is this postcode in our service area", register a function in customValidators and reference it by name from the schema:
import { createForm, type CustomValidator } from '@birchui/forms';
const inServiceArea: CustomValidator = async (value, { params }) => {
const response = await fetch(`/api/coverage?postcode=${encodeURIComponent(String(value))}`);
const { covered } = (await response.json()) as { covered: boolean };
return covered ? true : `We do not serve ${String(value)} yet. ${String(params?.hint ?? '')}`.trim();
};
createForm(container, {
schema: {
elements: [
{
type: 'text',
name: 'postcode',
title: 'Postcode',
required: true,
validators: [{ type: 'custom', name: 'inServiceArea', params: { hint: 'Call 0161 496 0000 to arrange a visit.' } }],
},
],
},
customValidators: { inServiceArea },
});A custom validator receives the value and a context with the field name, a copy of the form data, the field schema and the params from the schema. It can be synchronous or return a promise, and its result means:
| Result | Meaning |
|---|---|
true, null or undefined |
Valid. |
false |
Invalid, with the validator's message or "This value is not valid." |
| A non-empty string | Invalid, with that string as the message. |
Custom validators run after the built-in rules and expression validators have passed, only on visible, enabled fields with a value. When the user keeps typing while a check is still running, older results are discarded, so a slow response never overwrites a newer one. If a validator throws or rejects, or the schema names one that is not registered, the problem is reported through formError and the value is accepted.
Because schemas only reference validators by name, they stay JSON and can be edited in the Form Builder, while the code lives in your app.
When validation runs#
validateOn controls when a field is first checked:
| Value | Behaviour |
|---|---|
'blur' (default) |
When focus leaves the field. |
'change' |
On every change. |
'submit' |
Only when the user presses Next or Submit. |
Once a field shows an error, it is re-checked on every change, so the message disappears as soon as the problem is fixed. Pressing Next validates the current page and stays there if anything is wrong. Submitting validates every visible page.
How errors are shown#
- The message appears below the field, which gets
aria-invalid="true", and the message is linked to the control witharia-describedby. - After a failed Next or Submit, an error summary appears at the top of the form, titled "Please correct the following", with a link to each field. It is announced by screen readers, and it updates as errors are fixed.
- Focus moves to the first invalid field, switching to its page if needed and expanding any collapsed panel around it.
Turn the summary off with showErrorSummary: false if you show errors your own way, for example in a toast.
Hidden and disabled fields#
Fields that are hidden by visibleIf, on a hidden page, or disabled by enableIf or readOnly are never validated, and neither are hidden fields. clearHiddenValues decides what happens to answers of questions that become hidden:
| Value | Behaviour |
|---|---|
'onSubmit' (default) |
Answers are kept while the user fills in the form, so showing the question again restores them, and they are left out of the submitted data. |
'onHidden' |
Answers are cleared as soon as the question is hidden. |
'never' |
Answers are kept and submitted. |
getData() always returns the current values, including those of hidden questions; the formSubmit payload and the result of submit() apply clearHiddenValues.
Validate from code#
const { valid, errors } = await form.validate();
if (!valid) console.table(errors);
const result = await form.submit();
if (result.valid) await saveClaim(result.data);| Method | Purpose |
|---|---|
validate() |
Validates every visible page without submitting and resolves to { valid, errors }. Errors are shown next to their fields. |
submit() |
Validates, and if valid emits formSubmit and resolves to { valid, errors, data }. On errors it shows the summary and focuses the first invalid field. |
getErrors() |
The errors currently shown. |
focusField(name) |
Moves to a field's page and focuses it. |
Each error is a FieldError:
name is the field's data path, for example lineItems[1].amount inside a repeating section, and page is the index of its page. The validate event fires with the same payload after every validation pass.
Validate again on the server#
Client-side validation is for the user. Before you trust the data, check it again on the server. The expression engine has no DOM dependencies, so you can re-run the same rules in Node with evaluateExpression(), and your custom validators are your own functions to call there too.
Check schemas before you ship#
validateSchema(schema, options?) checks the schema itself, not the answers. Run it in a unit test for every form you ship, or before saving a schema edited by users:
import { validateSchema } from '@birchui/forms';
import { describe, expect, it } from 'vitest';
import { claimForm } from '../src/forms/claim';
describe('claim form schema', () => {
it('has no schema errors', () => {
const errors = validateSchema(claimForm, { functions: ['businessDaysBetween'] }).filter(
(issue) => issue.severity === 'error',
);
expect(errors).toEqual([]);
});
});Each issue has a path such as pages[1].elements[3].visibleIf, a message and a severity:
| Severity | Examples |
|---|---|
'error' |
Unknown element type, missing or duplicate name, choice field without choices, matrix without rows or columns, computed field without an expression, min greater than max, invalid pattern, expression syntax error, unknown function, unknown validator type. |
'warning' |
A name that does not follow the naming rule, a page without a name, a reference to a field that does not exist. |
The Form Builder's JSON tab runs the same check before it applies an edit.