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
| Parameter | Type | Description |
|---|---|---|
fn | (value: T, info: Info) => boolean | The check. value is already validated and transformed |
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
- To reuse a check, wrap it in a function — see Custom rules & schemas.
- For database or API calls use
checkAsync. - An exception inside
fnis 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'))),
});