示例: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 添加此验证?
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;
}),
});