如果 Yup.map() 不存在,如何在 React 中为 Map 创建 Yup 验证?

问题描述 投票:0回答:1
我有一个名为“myMapField”的字段,它需要是一个带有字符串键到字符串值的映射,并且我还需要根据其他名为“myArrayField”的字段中的元素验证映射中的键。

示例:myMapField 看起来像

{"employee1": "code1", "employee2": "code2"}
myArrayField 看起来像

["employee1", "employee2", "employee3"]
在上面,myMapField 应该具有字符串键到字符串值的类型,并且其中的键应该是基于某些条件过滤的 myArrayField 值的子集。

下面是适用于数组字段的验证架构,现在我想添加映射字段的验证。

const validationSchema = Yup.object().shape({ myArrayField: Yup.array() .of(Yup.string()) .min(1, 'This Field is Required') .required('This Field is Required'), myMapField: Yup. // some validation here to check type of key-value and check keys of myMapField to be subset of values in myArrayField });
如果没有 Yup.map(),如何为 myMapField 添加此验证?

reactjs validation yup
1个回答
0
投票
您可以使用

Schema.test 进行自定义验证

然后使用

this.parent

 访问 
myArrayField

最后使用js来检查地图是否有效,就像你所希望的那样。

const schema = yup.object().shape({ myArrayField: yup .array() .of(yup.string()) .min(1, "This Field is Required") .required("This Field is Required"), myMapField: yup.object().test("validMap", "Map is invalid", function (val) { const arrayFieldValue = this.parent.myArrayField; // check function const isInvalid = Object.keys(val).some((key) => { if (!arrayFieldValue.includes(key)) { return true; } }); return !isInvalid; }), });

演示

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