Zod必填输入验证未触发问题求助
Zod空字符串验证不生效的原因及解决方法
你当前的问题核心在于:Zod的z.string()默认将空字符串""判定为有效的字符串类型,你设置的required_error仅在输入为undefined或null时触发,空字符串不属于这个触发范围,所以safeParse("")会返回success: true。
解决方法
有两种常用方式来约束空字符串:
- 使用
min()方法限制最小长度
这是最直接的方式,指定字符串至少要有1个字符:
const nameSchema = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }).min(1, "Name cannot be empty"); console.log(nameSchema.safeParse("")); // 返回:{ success: false, error: [ZodError] },错误信息为"Name cannot be empty"
- 用
refine()自定义验证规则
如果需要更严格的校验(比如不允许全空格的字符串),可以用自定义验证逻辑:
const nameSchema = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }).refine(val => val.trim().length > 0, { message: "Name cannot be empty or consist of only whitespace" }); console.log(nameSchema.safeParse(" ")); // 返回验证失败,错误信息为自定义内容
补充说明
required_error的作用场景是未提供有效值,比如字段缺失、传入null或undefined;而空字符串属于“提供了值但值为空”,需要额外添加长度或自定义规则来拦截。
内容的提问来源于stack exchange,提问作者Mike Chan
相关产品推荐
相关产品推荐

