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

如何修复Formik中单选按钮组的验证失效问题?

问题分析与修复方案

你的代码存在几个关键问题,导致选中选项后仍触发验证错误:

1. RadioGroup未关联Formik状态

你在RadioGroup中使用了未定义的value和handleChange变量,没有绑定到Formik的表单状态和处理函数,导致选中选项后表单值无法更新。

2. 第三个单选按钮缺少value属性

最后一个<FormControlLabel>没有设置value,选中它时account字段会被设为空字符串,直接触发Yup的必填验证规则。


修复后的完整代码

验证Schema(无需修改)

const SignupSchema = Yup.object().shape({
  account: Yup.string().required('You must select an option'),
});

Formik组件修复后代码

<Formik
  initialValues={{
    account: '',
  }}
  validationSchema={SignupSchema}
  onSubmit={(values) => {
    console.log(values);
    window.location.replace('/SelectProfileType');
  }}
>
  {({ errors, touched, formik }) => (
    <Form>
      <ConnectedFocusError />
      <FormControl>
        <RadioGroup
          aria-labelledby='demo-controlled-radio-buttons-group'
          name='account'
          // 绑定Formik的account字段值
          value={formik.values.account}
          // 绑定Formik的变更处理函数
          onChange={formik.handleChange}
        >
          <FormControlLabel
            value='artist'
            name='account'
            control={<Radio />}
            label='Artist'
          />
          <br />
          <FormControlLabel
            value='golpher'
            name='account'
            control={<Radio />}
            label='Golpher'
          />
          <br />
          {/* 为第三个单选按钮添加唯一value和标签 */}
          <FormControlLabel
            value='other'
            name='account'
            control={<Radio />}
            label='Other'
          />
        </RadioGroup>
        <ErrorMessage name='account' />
      </FormControl>
      <Button type='submit' variant='contained'>
        Sign Up
      </Button>
    </Form>
  )}
</Formik>

额外注意事项

  • 所有单选按钮必须设置唯一的value值,确保Formik能正确捕获选中项
  • RadioGroup的name属性要与表单字段名account保持一致,保证状态同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:29:58