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
| Parameter | Type | Description |
|---|---|---|
schema | Schema | The schema to validate against |
value | unknown | Any data |
options | Options | { all?: boolean } — as in validate |
Returns
A Promise with the same result as validate: { valid, data, errors, issues }.
How it works
- All synchronous checks run first.
- Async checks of a field run only if the synchronous checks of that field passed — no needless database queries.
- Async checks of different fields run in parallel.
- If an async check throws,
validateAsyncrejects 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
- validate
- parseAsync — async version of parse
- checkAsync