Skip to content

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 ​

ParameterTypeDescription
schemaSchemaThe schema to validate against
valueunknownAny data: a form object, req.body, a string…
optionsOptionsOptional settings, see below

Options ​

OptionTypeDefaultDescription
allbooleanfalseCollect all errors of a field in issues instead of stopping at the first one. errors still holds the first
messagesRecord<string, Message>—Messages for this call only — e.g. the language of the current request. Missing ones come from setMessages
labelsRecord<string, string>—Field names for {label} by path: { email: 'Email', 'address.city': 'City' }. See label
maxDepthnumber256Maximum nesting of recursive lazy schemas
abortEarlybooleanfalseStop validation at the first error. The result has one error — faster on the server when details aren't needed. Not for forms

Returns ​

FieldTypeDescription
validbooleantrue if there are no errors
dataT | undefinedCleaned data: trim, coerce and defaults applied, unknown keys removed. undefined on error
errorsRecord<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 ''
issuesIssue[]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 removed

All 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; // 2

See also ​