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

Yup搭配react-hook-form如何实现表单内的条件必填字段?

实现方案

1. 调整Yup校验规则,新增条件必填逻辑

把原来固定必填的radioG3改成依赖radioG2取值的条件校验,使用Yup内置的when方法实现:

const schema = yup.object().shape({
  radioG1: yup.string().required("请选择一名复仇者"),
  radioG2: yup.string().required("请选择一名复仇者"),
  // 新增条件校验:当radioG2取值为「其他」时,radioG3才必填
  radioG3: yup.string().when('radioG2', {
    is: '其他', // 触发必填的条件:radioG2的值等于「其他」
    then: (schema) => schema.required('请选择一名其他复仇者'),
    otherwise: (schema) => schema.notRequired()
  })
});

2. 给radioG2新增「其他」选项

在原有radioG2的单选组中添加对应选项,供用户选择:

<RadioGroup {...field}>
  <FormControlLabel
    value="Thor"
    control={<Radio />}
    label="雷神"
  />
  <FormControlLabel
    value="Black Widow"
    control={<Radio />}
    label="黑寡妇"
  />
  {/* 新增其他选项 */}
  <FormControlLabel
    value="其他"
    control={<Radio />}
    label="其他"
  />
</RadioGroup>

3. 联动radioG2取值动态控制radioG3显示

不需要单独维护show状态,直接用react-hook-form提供的watch方法监听radioG2的取值,自动判断是否渲染第三组单选框:

// 在App组件内获取watch方法
const { handleSubmit, control, watch, formState: { errors } } = methods;
// 监听radioG2的取值
const radioG2Value = watch('radioG2');

把原来手动点击切换显示的逻辑替换为取值判断:

<Box mt={2} mb={2}>
  {/* 只有radioG2选了「其他」才显示第三组单选框 */}
  {radioG2Value === '其他' && <OtherAvengers control={control} errors={errors} />}
</Box>

额外说明

你原有配置里的shouldUnregister: true已经符合需求,字段隐藏时会自动从表单注册列表中移除,即使没加条件校验也不会触发隐藏字段的校验规则,搭配Yup条件校验可以实现双重保障。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:42:03