如何处理Zod可选字段中字符串类型"undefined"的验证问题?
Zod处理字符串"undefined"边缘场景的最简方案
当传入的是字符串类型的"undefined"时,z.string().time().optional()会验证失败——因为optional()只认原始类型的undefined,而字符串"undefined"会被time()判定为无效时间格式,直接触发验证失败。
最简解决办法是先把字符串"undefined"转换成原始undefined,再走后续验证,用Zod的preprocess或者transform都能实现,其中preprocess写法更直观:
const schema = z.preprocess( (value) => value === "undefined" ? undefined : value, z.string().time().optional() );
如果喜欢链式调用风格,用transform配合pipe也可以:
const schema = z.string() .transform(val => val === "undefined" ? undefined : val) .pipe(z.string().time().optional());
两种写法效果一致:若输入是字符串"undefined",就转成原始undefined,此时optional()会直接通过;若是其他字符串,则继续用time()验证格式是否合法。
内容的提问来源于stack exchange,提问作者Clemens Rosenow
相关产品推荐
相关产品推荐

