validate
Validates data against a schema and returns the result: whether it is valid, the cleaned data and the errors. Never throws because of invalid data.
Signature
ts
function validate<S extends Schema>(schema: S, value: unknown, options?: Options): Result<Infer<S>>Parameters
| Parameter | Type | Description |
|---|---|---|
schema | Schema | The schema to validate against |
value | unknown | Any data: a form object, req.body, a string… |
options | Options | Optional settings, see below |
Options
| Option | Type | Default | Description |
|---|---|---|---|
all | boolean | false | Collect all errors of a field in issues instead of stopping at the first one. errors still holds the first |
messages | Record<string, Message> | — | Messages for this call only — e.g. the language of the current request. Missing ones come from setMessages |
labels | Record<string, string> | — | Field names for {label} by path: { email: 'Email', 'address.city': 'City' }. See label |
maxDepth | number | 256 | Maximum nesting of recursive lazy schemas |
abortEarly | boolean | false | Stop validation at the first error. The result has one error — faster on the server when details aren't needed. Not for forms |
Returns
| Field | Type | Description |
|---|---|---|
valid | boolean | true if there are no errors |
data | T | undefined | Cleaned data: trim, coerce and defaults applied, unknown keys removed. undefined on error |
errors | Record<string, string> | The first error of each field. The key is a dot path: name, address.city, items.0.title. An error of the value itself is under '' |
issues | Issue[] | All errors in order: { code, message, path, params }, where path is an array (['items', 0, 'title']) and params are the rule parameters ({ min: 8 }) |
If the schema contains checkAsync, validate throws — use validateAsync.
Examples
A browser form
ts
const Login = object({
email: pipe(string(), trim(), email()),
password: pipe(string(), minLength(8)),
});
const result = validate(Login, { email: 'bad', password: '123' });
result.valid; // false
result.errors; // { email: 'Invalid email', password: 'Must be at least 8 characters long' }Successful validation
ts
const result = validate(Login, { email: ' Ivan@Mail.ru ', password: '12345678', remember: 'on' });
result.valid; // true
result.data; // { email: 'Ivan@Mail.ru', password: '12345678' } — trimmed, unknown key removedAll errors of a field
ts
const Code = pipe(string(), length(6), pattern(/^\d+$/));
validate(Code, 'abc').issues.length; // 1
validate(Code, 'abc', { all: true }).issues.length; // 2See also
- validateAsync — the same for async checks
- parse — returns data or throws
- TypeScript — narrowing the result