You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于单选框选择在Zod中实现文件输入框的条件验证?

基于单选框选择实现Zod+React Hook Forms的文件输入条件验证

要实现当businessType选择为"PVT Ltd"时form120必填的需求,你可以通过以下两种简洁方式实现:

方法一:Schema全局refine校验

直接在整个表单Schema上添加条件校验规则,针对业务类型的不同情况校验form120字段:

const formScheme = z.object({
  businessType: z.enum(["PVT Ltd", "Partnership", "Sole Proprietor"], { 
    required_error: 'Business Type is required.' 
  }),
  form120: z
    .any()
    .optional()
    // 优化文件格式校验逻辑
    .refine(file => {
      if (!file || file.length === 0) return true;
      return file[0]?.type === 'application/pdf';
    }, 'Must be a PDF.')
    // 优化文件大小校验逻辑
    .refine(file => {
      if (!file || file.length === 0) return true;
      return file[0]?.size <= 3 * 1024 * 1024; // 3MB
    }, 'Max file size is 3MB.'),
})
// 添加全局条件必填校验
.refine(data => {
  if (data.businessType === "PVT Ltd") {
    return data.form120 && data.form120.length === 1;
  }
  return true;
}, {
  message: 'Form 120 is required for PVT Ltd.',
  path: ['form120'] // 指定错误提示关联到form120字段
});

方法二:使用dependentRequired(Zod v3.20+支持)

如果你的Zod版本在v3.20及以上,可以用dependentRequired定义字段依赖关系,写法更简洁:

const formScheme = z.object({
  businessType: z.enum(["PVT Ltd", "Partnership", "Sole Proprietor"], { 
    required_error: 'Business Type is required.' 
  }),
  form120: z
    .any()
    .optional()
    .refine(file => {
      if (!file || file.length === 0) return true;
      return file[0]?.type === 'application/pdf';
    }, 'Must be a PDF.')
    .refine(file => {
      if (!file || file.length === 0) return true;
      return file[0]?.size <= 3 * 1024 * 1024;
    }, 'Max file size is 3MB.'),
})
.dependentRequired({
  // 当businessType为PVT Ltd时,form120必须存在
  form120: (data) => data.businessType === "PVT Ltd"
});

配合React Hook Forms使用

在组件中用zodResolver解析Schema即可生效:

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

const { register, handleSubmit, formState: { errors } } = useForm({
  resolver: zodResolver(formScheme),
});

这样当用户选择"PVT Ltd"但未上传对应文件时,错误提示会精准关联到form120输入框,符合表单交互预期。

内容的提问来源于stack exchange,提问作者Kavindu Wijesekara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 17:22:36