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

如何基于Checkbox组件的勾选值配置Yup校验规则?

基于Checkbox勾选值动态配置Yup表单校验

当然可以实现,借助Yup的when方法就能根据checkbox的勾选状态,动态控制其他字段的校验规则。

修改后的校验Schema

const validationSchema = Yup.object().shape({
  checkbox: Yup.bool().oneOf([true], 'You need to accept the terms and conditions'),
  // 根据checkbox状态动态控制first_name的必填性
  first_name: Yup.string().when('checkbox', {
    is: true,
    then: schema => schema.required("First Name is required"),
    otherwise: schema => schema.notRequired()
  }),
  last_name: Yup.string().when('checkbox', {
    is: true,
    then: schema => schema.required("Last name is required"),
    otherwise: schema => schema.notRequired()
  }),
  email: Yup.string().when('checkbox', {
    is: true,
    then: schema => schema.required("Email is required").email("Email is invalid"),
    otherwise: schema => schema.notRequired()
  }),
  phone: Yup.string().when('checkbox', {
    is: true,
    then: schema => schema.required("Phone is required"),
    otherwise: schema => schema.notRequired()
  }),
});

核心逻辑说明

  • when方法用于关联依赖字段(这里是checkbox)和目标字段的校验规则。
  • is: true指定触发条件:当checkbox被勾选时,执行then中的规则(设置为必填);未勾选时,执行otherwise(取消必填要求)。
  • 如果你的需求是未勾选checkbox时才校验字段,只需将is的值改为false即可。

表单组件适配

原有的Checkbox组件和错误提示代码无需大幅修改,只要你的表单状态管理(如Formik)能正确绑定这个schema,就能自动根据checkbox的状态触发对应的校验逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:40:08