createSchema
Creates your own schema from a validation function. Such a schema works everywhere the built-in ones do: in object, pipe, optional — and supports Standard Schema.
Signature
ts
function createSchema<T>(run: (value: unknown, ctx: Ctx, path: Path, parent: unknown) => T | Fail): Schema<T>
function fail(ctx: Ctx, path: Path, code: string, msg?: Message, params?: Record<string, unknown>): Fail
function isEmpty(value: unknown): booleanParameters
run parameter | Description |
|---|---|
value | The value to validate — can be anything |
ctx, path | Pass them to fail on error and to nested schemas |
parent | The object containing the value (raw input) |
run returns the value (it may be transformed) or the result of fail(...).
fail(ctx, path, code, msg?, params?)— records an error with codecode. The text comes frommsgor from thesetMessagesmessages by code;paramsfill{params}.isEmpty(value)—trueforundefined,nulland'': this is how built-in schemas behave, see Empty values.
Examples
ts
import { createSchema, fail, isEmpty, setMessages, type Message } from 'tinyval';
export const bigint = (msg?: Message) =>
createSchema<bigint>((value, ctx, path) => {
if (isEmpty(value)) return fail(ctx, path, 'required', msg);
if (typeof value !== 'bigint') return fail(ctx, path, 'bigint', msg);
return value;
});
setMessages({ bigint: 'Must be a bigint' });ts
// slug: trims, lowercases and validates
export const slug = (msg?: Message) =>
createSchema<string>((value, ctx, path) => {
if (isEmpty(value)) return fail(ctx, path, 'required', msg);
const s = String(value).trim().toLowerCase();
return /^[a-z0-9]+(-[a-z0-9]+)*$/.test(s) ? s : fail(ctx, path, 'pattern', msg);
});See also
- Custom rules & schemas — when
checkis enough - Standard Schema