是的.mixed()不与兄弟姐妹一起工作

问题描述 投票:0回答:1

我的数据结构如下所示:

{
  foo: true,
  bar: {
    baz: [{label: 'mario', url: 'https://nintendo.com'}]
  }
}

我的yup验证器看起来像这样:

  const schema = yup.object().shape({
    foo: yup.boolean(),
    bar: yup.mixed().when('foo', {
      is: true,
      then: yup.object().shape({
        baz: yup.array.of(
          yup.object().shape({
            label: yup.string.required(),
            url: yup.url().required()
          })
        )
      }),
      otherwise: yup.object().nullable(true)
    })
  })

但验证不适用于bar.baz;如果footrue,如果没有给出带有所需对象的数组,bar就不会抛出错误。

如果我将bar设置为以其他方式验证,请说:

  bar: yup.mixed().when('foo', {
    is: true,
    then: yup.string().required()
    otherwise: yup.string.nullable(true)
  })

它按预期为bar抛出一个错误。我错过了什么?

javascript validation formik yup
1个回答
0
投票

when()只能访问同一级别的房产。来自the documentation

mixed.when(keys:string | Array,builder:object |(value,schema)=> Schema):Schema

根据兄弟或兄弟子字段调整架构。您可以提供一个对象文字,其中键是值或匹配器函数,然后提供真实的模式和/或其他用于失败条件。

这就是为什么你的第二个例子有效(因为barfoo是兄弟姐妹)。一种可能的解决方案是重新排列数据,以便foobaz是兄弟姐妹。

至少有one issue on Yup's Github,作者建议通过Yup的上下文参数传递数据,但我不认为使用Formik和validationSchema道具是可能的,假设你正在使用它。

© www.soinside.com 2019 - 2024. All rights reserved.