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

如何在Yup嵌套Schema中基于外层值验证hobbyLikes字段

解决方法

你遇到的问题是无法在嵌套的hobbyLikes验证规则里访问外层的mySelection值,核心原因是当前字段处于更深的嵌套层级,直接引用mySelection会找不到变量。这里提供两种可行的实现方式:

方式一:使用相对路径引用外层字段

Yup支持通过相对路径(类似文件系统的路径)访问父级对象的字段,对于你的场景,../mySelection就指向当前hobby对象所在的myGroups数组项的mySelection字段。

修正后的完整Schema如下:

const myValSchema = Yup.object().shape({
  myGroups: Yup.array()
    .of(
      Yup.object().shape({
        myName: Yup.string().required('Name is required'),
        mySelection: Yup.number().required('Selection is required'),          
        myHobbies: Yup.array().of(
          Yup.object().shape({
            hobbyName: Yup.string().required('Hobby name is required'),
            hobbyLikes: Yup.number()
              .nullable()
              .when("../mySelection", {
                is: (mySelection) => mySelection === 99,
                then: Yup.number()
                  .typeError('Value must be a number')
                  .required('Likes is required')
                  .positive(),
              }),
          })
        )
      })
    )
});

方式二:通过上下文参数获取父级值

如果相对路径的写法不太直观,也可以利用when方法的第二个参数(上下文对象)逐层获取父级对象,进而拿到mySelection的值:

hobbyLikes: Yup.number()
  .nullable()
  .when("dummy", {
    is: (_, context) => context.parent.parent.mySelection === 99,
    then: Yup.number()
      .typeError('Value must be a number')
      .required('Likes is required')
      .positive(),
  })

这里context.parent是当前的hobby对象,context.parent.parent就是包含myHobbies和mySelection的外层对象。

两种方式都能实现需求,推荐用第一种相对路径的写法,更简洁易懂。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:25:22