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

Yup使用.when()通过key访问其他对象字段值的方法

Yup跨嵌套对象条件校验字段引用方法

问题原因

.when()方法默认以当前定义校验规则的字段所在的对象层级为起点解析引用路径。你在orgInfo对象内部定义companyName的校验规则时,直接写personInfo.customerType,Yup会尝试查找orgInfo.personInfo.customerType路径,无法匹配到根层级下的personInfo.customerType字段,导致校验不生效。

可用解决方案

根据你使用的Yup版本选择对应写法即可:

方法1:根路径引用(推荐,适用于Yup v1.0及以上版本)

在引用字段的路径前加$前缀,代表直接从整个校验Schema的根层级开始查找字段,不需要手动计算相对层级,后续调整嵌套结构也不容易出现路径错误。
修正后的完整Schema代码:

yup.object({
  personInfo: yup.object({
    customerType: yup.string().required(i18next.t("This field is mandatory"))
  }),
  orgInfo: yup.object({
    // 加$前缀,从根层级定位目标字段
    companyName: yup.string().when("$personInfo.customerType", {
      is: customerType => customerType !== CustomerTypes.STAFF,
      then: yup.string().required("This field is mandatory"),
      otherwise: yup.string()
    })
 })
})

方法2:相对路径跳转(兼容所有Yup版本)

如果使用v1以下的旧版本Yup,可以通过../向上跳转层级:companyName属于orgInfo对象,orgInfo和personInfo同属根层级,加一个../即可跳回根层级,再拼接目标字段路径就能正确引用。
对应代码:

yup.object({
  personInfo: yup.object({
    customerType: yup.string().required(i18next.t("This field is mandatory"))
  }),
  orgInfo: yup.object({
    // ../ 从orgInfo层级跳回根层级,再定位personInfo下的字段
    companyName: yup.string().when("../personInfo.customerType", {
      is: customerType => customerType !== CustomerTypes.STAFF,
      then: yup.string().required("This field is mandatory"),
      otherwise: yup.string()
    })
 })
})

注意事项

  • 如果后续在orgInfo外层新增其他嵌套结构,使用相对路径写法时需要对应增加../的数量,否则会出现路径匹配失败的问题;根路径$写法不受嵌套深度影响,维护成本更低。
  • 路径引用配置正确后,is判断逻辑、then/otherwise分支规则不需要做额外调整,即可正常获取目标字段值触发条件校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:48:15