Valibot 是一个 TypeScript 友好的模块化 schema 校验库,核心特点是可 tree-shaking,只打包实际用到的函数,从而获得很小的体积(资料给出的对比中基础表单约 1.4 KB,Zod 约 12 KB,Yup 约 15 KB)。
安装:npm install valibot,通过 import * as v from 'valibot' 使用。
主要能力:
- 基础 schema:string、number、boolean、null_、undefined_、bigint、symbol、date。
- 组合结构:object、strictObject、looseObject、array、tuple、union、variant(可辨识联合)、intersect。
- 修饰:optional、nullable、nullish,并可带默认值。
- 校验与转换:用 v.pipe() 串联,如 minLength、maxLength、email、url、uuid、regex、startsWith、endsWith、includes、trim、toLowerCase、toUpperCase;数字的 minValue、maxValue、integer、multipleOf、finite、safeInteger。pipe 中顺序会影响结果(例如先 trim 再 email 校验)。
- 自定义:v.check() 自定义断言,v.transform() 自定义转换,可组合出密码强度等自定义 schema。
- 执行 API:parse()(失败抛错,可捕获 ValiError 查看 issues)、safeParse()(返回 success/output/issues)、is()(类型守卫)。
- 类型推断:v.InferOutput、v.InferInput 从 schema 推导输入输出类型。
- 跨字段校验:v.forward 与 v.partialCheck,例如校验两次密码一致。
常见场景:用户注册(邮箱、密码规则、年龄、条款同意)、API 响应结构校验、环境变量校验(结合 transform(Number)、integer 等),以及通过 @hookform/resolvers/valibot 的 valibotResolver 集成 React Hook Form。
限制说明:官方未在资料中提供收费、价格或授权信息;性能基准、浏览器与运行时兼容范围、包体积的具体测量条件均暂未提供。