Skip to content

check ​

A custom synchronous check. The function returns true if the value is valid.

Signature ​

ts
function check<T>(fn: (value: T, info: Info) => boolean, msg?: Message): Action<T>

interface Info {
  parent: unknown; // the object containing the field (raw input)
  root: unknown;   // all data passed to validate
}

Parameters ​

ParameterTypeDescription
fn(value: T, info: Info) => booleanThe check. value is already validated and transformed
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 ​

  • To reuse a check, wrap it in a function — see Custom rules & schemas.
  • For database or API calls use checkAsync.
  • An exception inside fn is not turned into a validation error, it is rethrown.

Examples ​

Age 18+ ​

ts
const adult = check<Date>((birth) => {
  const d = new Date();
  d.setFullYear(d.getFullYear() - 18);
  return birth <= d;
}, '18+ only');

object({ birthday: pipe(coerce.date(), adult) });

Depends on another field ​

ts
object({
  delivery: oneOf(['pickup', 'courier']),
  address: optional(pipe(string(), check((v, { parent }) => parent.delivery === 'courier', 'Address is only for courier delivery'))),
});

See also ​