如果我理解正确,那么应该这样做。
const mySchema = yup.object({
values: yup.array().of(
yup.object({
value1: yup
.string()
.test(
"test-1",
"error: required if array length > 1",
(value, context) => {
const [, values] = context.from;
const {
value: { values: arrayValues }
} = values;
// ONLY IF ARRAY LENGTH > 1
if (arrayValues.length > 1) {
// valid only if value is provided
return !!value;
}
}
),
value2: yup.string().when("value1", {
// if value1 is provied, value2 should be provided too
is: (value1) => !!value1,
then: (value2) => value2.required()
})
})
)
});
// should pass
console.log(
mySchema.validateSync({
values: [
{ value1: "1", value2: "2" },
{ value1: "1", value2: "2" }
]
})
);
// ValidationError: error: required if array length > 1
console.log(
mySchema.validateSync({
values: [{ value1: "1", value2: "2" }, { value2: "2" }]
})
);
// ValidationError: values[1].value2 is a required field
console.log(
mySchema.validateSync({
values: [{ value1: "1", value2: "2" }, { value1: "1" }]
})
);
这里的关键是删除.required() 并在数组满足您的自定义条件时提供您自己的检查test()。
要访问.test() 内部的父值,请使用context.from
const [parent1, parent2, ...rest] = context.from;
Live Example