javascript - 是的,验证不同对象形状的数组
问题描述
我正在使用 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]"
]
如何解决这个问题?
解决方案
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
推荐阅读
- php - Wordpress 灯箱缩略图可点击
- python - 链接到 Excel 工作表并在工作表上更新约会时发送 SMS 文本的 Python API 脚本
- c# - 使用 dapper 插入多个对象
- xcode - 如何恢复 Xcode App Target“编译源”和“链接二进制与库”条目?
- http - 如何将字符串 url 传递到 kotlin 的 URL 中?
- java - 使用终端命令而不是双击运行 jar 文件
- java - 如果满足条件,是否有一种简单的方法可以将布尔值设置为 true?
- postgresql - 在 postgresql 11 中动态选择 HASH 分区
- json - 对于 Angular 6 项目,如何一次从 JSON 文件中获取一定数量的信息?
- python - 将一个列表中的两个子列表合并为一个子列表python