示例说明
Valibot 的管道隐喻让数据处理顺序一目了然:数据从上到下流过每个步骤,前面的输出是后面的输入。pipe 不仅能校验也能变换——toLowerCase 直接改变值;brand 给通过校验的字符串打上名义类型标记,让 UserId 与普通 string 在类型层面不可混用;v.json 甚至把字符串解析后再校验对象结构。
技术要点
- pipe 步骤按声明顺序依次执行
- brand 构造不可混淆的名义类型
- v.json 先解析再校验双层把关
代码解读
Email 管道依次修剪空白、转小写、断言非空并校验格式;UserId 要求合法 UUID 并品牌化。JsonBody 把外部字符串经 JSON 解析进对象校验,score 的数值范围由独立管道约束。safeParse 成功时 output 是变换后的最终形态,邮箱已是规范小写。
使用建议
变换步骤要放在校验之前,先归一化再检查更宽容。品牌类型适合贯穿多模块的实体标识。InferOutput 取的是管道终点类型,与 InferInput 的差异要留意。
代码示例
import * as v from 'valibot';
const Email = v.pipe(
v.string(),
v.trim(),
v.toLowerCase(),
v.nonEmpty(),
v.email('enter a valid email'),
);
const UserId = v.pipe(
v.string(),
v.uuid(),
v.brand('UserId'),
);
const JsonBody = v.pipe(
v.string(),
v.trim(),
v.json('body must be valid JSON'),
v.object({
id: UserId,
email: Email,
score: v.pipe(v.number(), v.min(0), v.max(100)),
}),
);
type UserRef = v.InferOutput<typeof JsonBody>;
const parsed = v.safeParse(JsonBody, JSON.stringify({
id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8',
email: ' [email protected] ',
score: 88,
}));
if (parsed.success) {
console.log(parsed.output.email, parsed.output.score);
} else {
for (const issue of parsed.issues) {
console.log(issue.path?.map((p) => p.key).join('.'), issue.message);
}
}