Skip to content

createSchema ​

用校验函数创建自定义 Schema。它可以在任何使用内置 Schema 的地方使用:object、pipe、optional —— 并且支持 Standard Schema。

签名 ​

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

参数 ​

run 参数说明
value要校验的值 —— 可以是任何值
ctx、path出错时传给 fail,也传给嵌套的 Schema
parent包含该值的对象(原始数据)

run 返回值(可以是转换后的值)或 fail(...) 的结果。

  • fail(ctx, path, code, msg?, params?) —— 记录代码为 code 的错误。文本来自 msg,或按代码来自 setMessages 的信息;params 用于替换 {参数}。
  • isEmpty(value) —— 对 undefined、null 和 '' 返回 true:内置 Schema 也是这样处理的,见 空值。

示例 ​

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);
  });

另请参阅 ​