Skip to content

validateAsync ​

The async version of validate. Required if the schema contains checkAsync — e.g. an "email is not taken" check with a database query.

Signature ​

ts
function validateAsync<S extends Schema>(schema: S, value: unknown, options?: Options): Promise<Result<Infer<S>>>

Parameters ​

ParameterTypeDescription
schemaSchemaThe schema to validate against
valueunknownAny data
optionsOptions{ all?: boolean } — as in validate

Returns ​

A Promise with the same result as validate: { valid, data, errors, issues }.

How it works ​

  1. All synchronous checks run first.
  2. Async checks of a field run only if the synchronous checks of that field passed — no needless database queries.
  3. Async checks of different fields run in parallel.
  4. If an async check throws, validateAsync rejects with that error.

validateAsync also works for schemas without async checks — it just returns a Promise.

If you don't know in advance whether a schema has async checks, use validateAny(schema, value, options): it returns the result right away, and a Promise only when there are async checks. Every check is called once.

Example ​

Sign-up ​

ts
const Signup = object({
  email: pipe(string(), email(), checkAsync(async (v) => !(await db.users.exists({ email: v })), 'Email is taken')),
  password: pipe(string(), minLength(8)),
});

const result = await validateAsync(Signup, req.body);

if (!result.valid) return res.status(422).json({ errors: result.errors });

See also ​