验证yup中不同对象形状的数组

时间:2019-10-04 14:10:24

标签: javascript reactjs formik yup

我正在使用formik进行表单验证,并遇到了数组验证中的一些问题。 这是我的表单结构

{
 flow: [
  { text: "hello"
  },
  { input: "world"
  },
  { buttons: [
       'hi',
       'hello'
     ]
  }
 ]
}

我必须为此创建验证架构。因此数组可以包含这些对象中的任何一个。

我尝试过

export const validationSchema = yup.object().shape({
  flow: yup.array().of(
      yup.mixed().oneOf([
        {
          text: yup.string().required('Enter text'),
        },
        {
          buttons: yup.array().of(yup.string().required('Enter button title')),,
        },
        {
          input: yup.string()
          ),
        }
      ])
  ),
});

但是出现以下错误:

flow:[

"flow[0] must be one of the following values: [object Object], [object Object]",
"flow[1] must be one of the following values: [object Object], [object Object]"

]

如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

我无法使用Yup实现此功能,我切换到hapi/joi并重写了我的两个应用(这很容易,因为它们之间的库有很多相似之处),我将Yup与它们一起使用,hapi / joi开箱即用地支持此功能以及其他惊人功能。

答案 1 :(得分:1)

import { array, object, string, lazy } from 'yup';    

const differentObjectsArraySchema = array().of(lazy((item) => {
    const { type } = item;

    // any other condition
    if (type === 'text') {
        return object({
            text: string(),
        });
    }

    if (type === 'buttons') {
        return object({
            buttons: array(),
        });
    }

    if (type === 'input') {
        return object({
            input: string(),
        });
    }
}));

来源:https://github.com/jquense/yup#yuplazyvalue-any--schema-lazy

答案 2 :(得分:0)

如果您查看oneOf方法的函数签名:

mixed.oneOf(arrayOfValues: Array<any>, message?: string | function): Schema

第一个参数是any的数组,因此任何值将在第一个参数的数组内有效。这是第二个message参数,只能是字符串/函数。

话虽这么说,您的代码看起来确实正确,所以我不确定为什么会收到任何错误。也许尝试添加一个消息参数,看看是否可以解决问题。如果出现错误,您收到的确切错误是什么?

答案 3 :(得分:0)

也许新的自定义架构类型是一种解决方案,但是带有自定义测试功能(带有anyof逻辑)的数组架构又如何呢?在下面的示例中,只是简单的有效性检查。 https://codesandbox.io/s/yup-anyof-array-w0cww