[英]Validation using Yup to check array length --> error if length === 1
[英]Yup validation of an array - values required only if array length is bigger than 1
我每行有 2 個下拉菜單,我可以動態添加和刪除第一行之外的行。 如果只有一行(從頭開始渲染)並且它是空的並且在以下情況下無法提交,我想提交表單:
或者
我正在使用是的驗證。
我試過用.test()檢查長度,但這個測試總是在檢查“必需”之后運行。
這就是我想要的:
const validationSchema = yup.object({
values:
yup.array()
.of(
yup.object({
value1: yup.string().required(), // ONLY IF ARRAY LENGTH > 1
value2: yup.string().required()// ONLY IF VALUE1 IS SELECTED
})
)});
如果我理解正確,那么應該這樣做。
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;
經過一些更改后,它現在可以工作了,但我無法擺脫“來自”上的 TypeScript 錯誤
value1: yup.string()
.test(
"test-1",
"error: required if array length > 1",
(value, context) => {
const arrayValues = context.from[1].value.values
if (arrayValues.length > 1) {
return !!value; }
return true;
}
),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.