---
title: 'Custom and async rules'
description: 'Register your own validation rules, ask a server with the async rule, depend on other fields and test a rule on its own.'
order: 6
---

import * as z from 'zod/mini';

# Custom and async rules

The [built-in rules](/docs/forms/validation) cover formats, ranges and cross-field checks. For a business requirement they do not cover, register a rule of your own with the engine. For a check that needs a server, use the built-in `async` rule, [below](#the-built-in-async-rule).

## Register a rule

A validation registration has the shape of every registration:

- `$type`: what authors write in a field's `rules`. A registration with `$type: 'postalCode'` handles `{ $type: 'postalCode' }`.
- `schema`: a [Standard Schema](https://standardschema.dev/) for the rule object. A form config that uses the rule is checked against it, so the options it declares are validated where the form is.
- `metadata`: a `name` and an optional `description`.
- `category` and `handler`: the handler returns the Zod Mini schema that checks the value. `params`, `dependsOn` and `defaultFor` are optional.

Pass registrations to `createFormEngine({ validations: [...] })`, or to `engine.extend({ validations: [...] })` to add them to an engine you have, as the example below does with the engine of the [quick start](/docs/forms/getting-started). They come after the built-in rules, so a registration with a built-in `$type` replaces it, and a later one replaces an earlier one without a warning. Nothing can be registered or removed once the engine is built.

Every element that extends `BaseFieldSchema` accepts a rule of any registered `$type`. When the engine validates a form config (`defineForm`, `validateForm`) it checks each rule against the registry: the `$type` must be registered and the rule must satisfy the registration's `schema`. The JSON Schema export (`generateFormConfigSchema`) lists each registered rule once, as the `validation-rule` definition that every element's `rules` refers to, so an editor offers custom rules too. A rule is listed with its options when its `schema` is Zod; a schema from another Standard Schema library is listed by its `$type` only.

```typescript
import * as z from 'zod/mini';
import type { ValidationRegistration } from '@schema-engine/forms';
import { engine as base } from './engine';

type PostalCodeRule = { $type: 'postalCode'; country?: 'us' | 'ca'; message?: string };

const postalCode: ValidationRegistration<PostalCodeRule> = {
	$type: 'postalCode',
	schema: z.looseObject({ $type: z.literal('postalCode'), country: z.optional(z.enum(['us', 'ca'])) }),
	metadata: { name: 'Postal code' },
	category: 'string',
	params: (rule) => ({ country: rule.country ?? 'us' }),
	handler: (rule) =>
		z.string().check(z.regex(rule.country === 'ca' ? /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ : /^\d{5}(?:-\d{4})?$/)),
};

export const engine = base.extend({ validations: [postalCode] });

export const form = engine.defineForm({
	id: 'address',
	steps: [
		{
			id: 'main',
			title: 'Address',
			elements: [
				{
					$type: 'input',
					id: 'postal-code',
					name: 'postalCode',
					rules: [{ $type: 'postalCode', country: 'ca', message: 'Enter a Canadian postal code' }],
				},
			],
		},
	],
});
```

A `$type` nothing registers is rejected when the form is validated, with the types that are registered: `No registration for $type 'postalcode'. Register it with createFormEngine({ validations: [...] }). Registered rules: required, minLength, ...`. The issue is at `steps[0].elements[0].rules[0].$type`. An option the registration's `schema` refuses is reported at its key, such as `steps[0].elements[0].rules[0].country`.

## What the form shows

The handler decides only whether the value passes. The text a schema carries, such as the message of a `z.regex`, is never shown. The engine reports an issue as data: the rule's `$type` as `type`, its `id` as `ruleId`, the `params` the registration exposes and the author's `message` when the rule has one. Words come from the [formatter](/docs/forms/issue-text), so a handler writes no message and never reads `rule.message` itself.

`params` is how a registration shares its options with that formatter. The built-in `minLength` returns `{ minLength: rule.value }`, named like the native constraint, so a sentence can say "at least 8 characters". Return only serializable values, and nothing for a rule whose options are configuration. The optional `message` hook decides the fallback text when the author gave none; return `reported` only for text that comes from outside the engine, such as the answer of an endpoint.

## Check with an algorithm

A rule is a good place for a checksum the built-in rules do not have. This one validates an IBAN with the ISO 7064 mod-97 check, so a typo is caught before the request:

```ts title="iban.ts"
import * as z from 'zod/mini';
import { createFormEngine, type ValidationRegistration } from '@schema-engine/forms';

type IbanRule = { $type: 'iban'; message?: string };

export function isValidIban(value: string): boolean {
	const iban = value.replaceAll(' ', '').toUpperCase();
	if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(iban)) return false;
	const rearranged = `${iban.slice(4)}${iban.slice(0, 4)}`;
	const digits = [...rearranged].map((char) => (/\d/.test(char) ? char : String(char.charCodeAt(0) - 55))).join('');
	let remainder = 0;
	for (const digit of digits) remainder = (remainder * 10 + Number(digit)) % 97;
	return remainder === 1;
}

const iban: ValidationRegistration<IbanRule> = {
	$type: 'iban',
	schema: z.looseObject({ $type: z.literal('iban') }),
	metadata: { name: 'IBAN', description: 'An IBAN with a valid mod-97 check.' },
	category: 'string',
	handler: () => z.string().check(z.refine(isValidIban)),
};

export const engine = createFormEngine({ validations: [iban] });
```

## Rules that read other fields

Every handler receives a `ValidationContext` as its second argument. Read other fields through `context.resolve`, which resolves a reference relative to the field being validated: a bare name is a sibling, a dotted name is absolute from the form root. `context.values` holds the whole form as a nested tree when a rule needs more than one reference.

```typescript
import * as z from 'zod/mini';
import { createFormEngine, type ValidationRegistration } from '@schema-engine/forms';

type ConfirmPasswordRule = { $type: 'confirmPassword'; message?: string };

const confirmPassword: ValidationRegistration<ConfirmPasswordRule> = {
	$type: 'confirmPassword',
	schema: z.looseObject({ $type: z.literal('confirmPassword') }),
	metadata: { name: 'Confirm password' },
	category: 'cross-field',
	dependsOn: () => ['password'],
	handler: (_rule, context) =>
		z.string().check(z.refine((confirmation) => context.resolve('password') === confirmation)),
};

export const engine = createFormEngine({ validations: [confirmPassword] });
```

Because the reference is relative, a rule authored once on a field inside an array reads its own row: `confirmPassword` on `accounts.1.confirm` resolves `password` to `accounts.1.password`.

`dependsOn` tells a renderer when to re-run the rule. Without it the rule still validates correctly, but only when its own field is validated, so correcting the password would not clear the error on the confirmation. With it, the error surfaces once the dependent field has been touched or the form submitted. Rules in a form run together, so a slow rule does not wait for the others.

## The built-in async rule

For a check that needs a server, use the built-in `async` rule. It sends the value, caches the answer, waits for the user to stop typing and re-validates when the fields it depends on change.

```ts title="async-rule.ts"
import type { AsyncRule } from '@schema-engine/forms';

export const usernameRule = {
	$type: 'async',
	url: '/api/check-username',
	method: 'POST',
	extraPayload: { validationType: 'premium' },
	expectedResponse: { valid: true },
	debounce: 500,
	cacheTTL: 300000,
	message: 'Username is already taken',
} satisfies AsyncRule;
```

| Property           | Type       | Description                                                           |
| ------------------ | ---------- | --------------------------------------------------------------------- |
| `url`              | `string`   | API endpoint for validation                                           |
| `method`           | `string`   | `GET`, `POST`, `PUT`, `PATCH` or `DELETE`                             |
| `headers`          | `object`   | Optional HTTP headers                                                 |
| `extraPayload`     | `object`   | Extra request fields. `value` and `dependsOn` are added automatically |
| `expectedResponse` | `object`   | The response body that means the value is valid                       |
| `dependencies`     | `string[]` | Fields that trigger re-validation when they change                    |
| `debounce`         | `number`   | Delay in ms before the request is made                                |
| `cacheTTL`         | `number`   | Cache time-to-live in milliseconds (default: 5 minutes)               |
| `disableCache`     | `boolean`  | Turn the cache off (default: false)                                   |
| `message`          | `string`   | The text to show when the server says the value is not valid          |

With `debounce`, a newer validation of the same field replaces a pending one and only the latest request is sent. A replaced validation of the same value shares that request's result. One of a different value has no result, neither a pass nor an issue, so a submit-time check superseded by a later edit never passes. Nothing is shown for it while the user types: each renderer shows the result for the latest value. Debouncing replaces pending timers; it does not cancel a request that has already started.

### Dependencies

`dependencies` are field references and resolve exactly like `relate`'s `fields`: a bare name is a sibling, including a sibling inside the declaring array row, and a dotted name is absolute from the form root. The request body carries a `dependsOn` object keyed by the reference as authored:

```json
{
	"value": "userInputValue",
	"dependsOn": {
		"username": "actualUsernameValue",
		"email": "actual@email.com"
	}
}
```

### Caching and outages

- Successful answers are cached for five minutes by default. The key is the URL and the request payload. Expired entries are evicted on cache reads and writes.
- A non-ok response or a network failure is not an answer about the value. The rule throws `ValidationUnavailable`, which is reported as a failure to run (`validate()` rejects), and it is never cached.

## A custom async rule

Use a registration when the check is not a request and a response the built-in rule can describe. Answer "taken" only when the server says so. A request that fails is not an answer, so throw `ValidationUnavailable`, as the built-in rule does, and the form reports that the check could not run:

```ts title="unique-username.ts"
import * as z from 'zod/mini';
import { createFormEngine, ValidationUnavailable, type ValidationRegistration } from '@schema-engine/forms';

type UniqueUsernameRule = { $type: 'uniqueUsername'; message?: string };

const uniqueUsername: ValidationRegistration<UniqueUsernameRule> = {
	$type: 'uniqueUsername',
	schema: z.looseObject({ $type: z.literal('uniqueUsername') }),
	metadata: { name: 'Unique username' },
	category: 'generic',
	handler: (rule, { fetch }) =>
		z.string().check(
			z.refine(async (username) => {
				let response: Response;
				try {
					response = await fetch('/api/check-username', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({ username }),
					});
				} catch (cause) {
					throw new ValidationUnavailable({ cause });
				}
				if (!response.ok) throw new ValidationUnavailable();
				const { available } = (await response.json()) as { available: boolean };
				return available;
			}),
		),
};

export const engine = createFormEngine({ validations: [uniqueUsername] });
```

The handler's second argument is the validation context. Its `fetch` is the engine's, so a CSRF policy and a test double apply to this request too.

## Test a rule

Build an engine with the rule and read the schema from its registry. The registry also answers what the form would report for the rule:

```typescript
import * as z from 'zod/mini';
import { describe, it, expect } from 'vitest';
import { createFormEngine, createValidationContext } from '@schema-engine/forms';

const postalCode = {
	$type: 'postalCode',
	schema: z.looseObject({ $type: z.literal('postalCode') }),
	metadata: { name: 'Postal code' },
	category: 'string',
	handler: () => z.string().check(z.regex(/^\d{5}(?:-\d{4})?$/)),
} as const;

const registry = createFormEngine({ validations: [postalCode] }).getValidationRegistry();

describe('postalCode', () => {
	const schema = registry.createSchema({ $type: 'postalCode' }, createValidationContext());

	it('accepts a ZIP and a ZIP+4', () => {
		expect(schema?.safeParse('12345').success).toBe(true);
		expect(schema?.safeParse('12345-6789').success).toBe(true);
	});

	it('rejects anything else', () => {
		expect(schema?.safeParse('1234').success).toBe(false);
		expect(schema?.safeParse('abcde').success).toBe(false);
	});

	it('reports the message the author wrote', () => {
		const rule = { $type: 'postalCode', message: 'Enter a ZIP code' };
		expect(registry.getRuleMessage(rule, undefined)).toBe('Enter a ZIP code');
	});
});
```

## The registry

The engine's validation registry is read-only. It lists what is registered but has no `register`, `unregister` or `clear`:

```ts title="registry-status.ts"
import { engine } from './iban';

const validationRegistry = engine.getValidationRegistry();

export const hasIban = validationRegistry.has('iban');
export const types = validationRegistry.keys();
export const stringValidations = validationRegistry.getByCategory('string');
```

To replace a rule, register another with the same `$type` later in the list, or `engine.extend({ validations: [...] })`, which returns a new engine and keeps the validations the source was created with. To drop one, build the engine without it.

To build a registry outside an engine, for a test, use `createValidationRegistry`. It holds only what you list. `createDefaultValidationRegistry` adds the built-in rules first:

```ts title="test-registry.ts"
import * as z from 'zod/mini';
import { createValidationContext, createValidationRegistry } from '@schema-engine/forms';

const testOnly = {
	$type: 'testOnly',
	schema: z.object({ $type: z.literal('testOnly') }),
	metadata: { name: 'Test only' },
	category: 'string',
	handler: () => z.string().check(z.minLength(1)),
} as const;

export const testRegistry = createValidationRegistry([testOnly]);

export const schema = testRegistry.createSchema({ $type: 'testOnly' }, createValidationContext());
```

## The endpoint

The endpoint of the built-in rule receives `value`, `dependsOn` when the rule has `dependencies`, and every key of `extraPayload`. It answers with the `expectedResponse` body when the value is valid, and `message` can carry the text to show when it is not:

```ts title="check-username-endpoint.ts"
const unavailable = new Set(['admin', 'root']);

export async function POST(request: Request): Promise<Response> {
	const { value } = (await request.json()) as { value: string };
	if (unavailable.has(value.toLowerCase())) {
		return Response.json({ valid: false, message: `Username "${value}" is not available` });
	}
	return Response.json({ valid: true });
}
```

## Where to go next

- [Validation](/docs/forms/validation): the built-in rules and presets.
- [Constraints](/docs/forms/constraints): show, hide or require a field from another value.
- [Issue text](/docs/forms/issue-text): word the issues a rule reports.
