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

使用useFieldArray钩子时如何在React Hook Form中验证数组字段

方案1:通过校验Schema定义规则(推荐)

使用Zod、Yup等校验库时,直接给对应数组字段添加最小长度限制即可,React Hook Form会自动关联useFieldArray的数据完成校验:

import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'

// 表单校验Schema定义
const formSchema = z.object({
  logic: z.array(
    z.object({
      // 给questions数组添加最小长度为1的校验规则
      questions: z.array(z.object({
        id: z.string()
      })).min(1, '至少需要添加一个问题')
    })
  )
})

// useForm绑定校验器
const { control, formState: { errors } } = useForm({
  resolver: zodResolver(formSchema),
  defaultValues: {
    logic: [{ questions: [] }] // 提前设置初始默认值,避免undefined引发的异常
  }
})

方案2:通过自定义validate规则实现(无需第三方校验库)

如果没有使用外部校验库,可以直接在useFieldArray的配置项中添加校验规则:

const { control, formState: { errors } } = useForm({
  defaultValues: {
    logic: [{ questions: [] }]
  }
})

const { fields, append, remove } = useFieldArray<FieldValues>({
  control, // 注意必须传入control参数,否则字段关联会异常
  name: `logic.${index}.questions`,
  rules: {
    validate: (value) => value.length > 0 || '至少需要添加一个问题'
  }
})

错误提示展示

校验不通过时,直接从formState.errors中读取对应字段的错误信息展示即可,handleSubmit默认会在校验失败时阻止提交逻辑执行:

<Box>
  { fields.map((field) => <Text key={field.id}>{ field.id }</Text> )}
  {/* 展示错误提示 */}
  {errors?.logic?.[index]?.questions && (
    <Text style={{ color: 'red' }}>{errors.logic[index].questions.message}</Text>
  )}
</Box>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 23:48:04