首页 > 解决方案 > 是的,验证不同对象形状的数组

问题描述

我正在使用 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()
          ),
        }
      ])
  ),
});

但是我得到以下作为formik错误:

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]"

]

如何解决这个问题?

标签: javascriptreactjsformikyup

解决方案


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


推荐阅读