Skip to content

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 ​

ParameterTypeDescription
fn(value: T, info: Info) => Promise<boolean> | booleanThe check. info — as in check
msgMessageCustom error message. A string with {params} or a function

Error codes ​

CodeWhenDefault message
invalidfn returned falseInvalid 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.
  • validate and parse throw for such a schema — use the async version.
  • It doesn't change the value: checkAsync only 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 ​