checkAsync
A custom async check: a database query, an external API. Works only with validateAsync and parseAsync.
Signature
ts
function checkAsync<T>(fn: (value: T, info: Info) => Promise<boolean> | boolean, msg?: Message): Action<T>Parameters
| Parameter | Type | Description |
|---|---|---|
fn | (value: T, info: Info) => Promise<boolean> | boolean | The check. info — as in check |
msg | Message | Custom error message. A string with {params} or a function |
Error codes
| Code | When | Default message |
|---|---|---|
invalid | fn returned false | Invalid value |
You can change the texts: see Messages & i18n.
Notes
- Runs after all synchronous rules of the field and only if they passed — an invalid email never reaches the database.
- Async checks of different fields run in parallel.
validateandparsethrow for such a schema — use the async version.- It doesn't change the value:
checkAsynconly checks.
Example
Unique email
ts
const Signup = object({
email: pipe(
string(),
trim(),
toLowerCase(),
email(),
checkAsync(async (v) => !(await db.users.exists({ email: v })), 'Email is already registered'),
),
});
const result = await validateAsync(Signup, req.body);See also
- validateAsync
- parseAsync
- check — sync version