Chapter 7
Validation
7.1 Validators#
type Validator<V> = (value: V, ctx: ValidationContext) => string | null | undefined | Promise<...>;
interface ValidationContext { control: Control<unknown>; getField?: (name: string) => Control<unknown> | undefined }
Return an error message, or null/undefined when valid. Validators run in order and stop at the first error.
required is checked before any validator.
new TextInput(ui, {
name: 'username', label: 'Username', required: true,
validators: [
(v) => (/^[a-z][a-z0-9_]{2,23}$/.test(v) ? null : 'Use 3–24 lowercase letters, digits or _.'),
async (v) => ((await api.isTaken(v)) ? 'That username is taken.' : null),
],
});
- Async: if the value changes while a check is in flight, the stale result is discarded.
- Exceptions: a throwing validator shows "Could not validate this field." and never leaks error details.
- Cross-field: use
ctx.getField(name)(available once the control belongs to aForm).
const matchesPassword: Validator<Secret> = (v, ctx) => {
const other = ctx.getField?.('password')?.getValue();
return other instanceof Secret && !v.equals(other) ? 'Passwords do not match.' : null;
};
7.2 When validation runs#
autovalidateMode (Form) |
Behaviour |
|---|---|
'onUserInteraction' (default) |
Each control uses its validateOn ('blur' by default). Once a touched field shows an error, it re-validates on every change so the error clears as soon as it's fixed. |
'always' |
Validate on every change, from the start. |
'disabled' |
Only on submit. |
Call control.validate() yourself to re-check a dependent field, e.g. revalidate "confirm password" when
"password" changes (the demo does this).
7.3 Validators from shared rules#
fromRule(rules, name) returns options including a validator built from the rule, so the browser runs the same
checks as the server. See §13.