Skip to content

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): boolean

Parameters ​

run parameterDescription
valueThe value to validate — can be anything
ctx, pathPass them to fail on error and to nested schemas
parentThe 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 code code. The text comes from msg or from the setMessages messages by code; params fill {params}.
  • isEmpty(value) — true for undefined, null and '': 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 ​