当布尔值为假时如何验证数字数组?
How to validate an array of numbers when a boolean is false?
我需要在检查布尔值时验证数字数组,但我在控制台中收到此错误:
Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
at yupToFormErrors (formik.esm.js:701)
这是我的 validationSchema。
export default yup.object<myFormikForm.FormValues>({
allowOther: yup.boolean(),
arrayNumbers: yup
.array<number, *>(
yup
.number()
.nullable(true)
.transform((value, originalValue) =>
originalValue === '' ? null : value,
)
.min(
minSize,
oneLine`
Must be greater or equal than
0
`,
),
)
.when('allowOther', (allowOther: boolean, schema) =>
allowOther
? schema
: schema
.required('Required')
.test(
'hasAtLeastOneValue',
'Specify at least one value',
value =>
Array.isArray(value) ? value.some(Number.isFinite) : true,
),
),
});
顺便说一句,表格工作正常,但我想摆脱这个错误,有什么想法吗?谢谢
您可以根据自己的情况使用 yup.ref()
。了解更多 here。
allowOther: Yup.boolean(),
arrayNumbers: Yup.array().nullable().min(Yup.ref('allowOther'), 'Must be greater or equal than 0').required(Yup.ref('allowOther'), "arrayNumbers are required"),
我需要在检查布尔值时验证数字数组,但我在控制台中收到此错误:
Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
at yupToFormErrors (formik.esm.js:701)
这是我的 validationSchema。
export default yup.object<myFormikForm.FormValues>({
allowOther: yup.boolean(),
arrayNumbers: yup
.array<number, *>(
yup
.number()
.nullable(true)
.transform((value, originalValue) =>
originalValue === '' ? null : value,
)
.min(
minSize,
oneLine`
Must be greater or equal than
0
`,
),
)
.when('allowOther', (allowOther: boolean, schema) =>
allowOther
? schema
: schema
.required('Required')
.test(
'hasAtLeastOneValue',
'Specify at least one value',
value =>
Array.isArray(value) ? value.some(Number.isFinite) : true,
),
),
});
顺便说一句,表格工作正常,但我想摆脱这个错误,有什么想法吗?谢谢
您可以根据自己的情况使用 yup.ref()
。了解更多 here。
allowOther: Yup.boolean(),
arrayNumbers: Yup.array().nullable().min(Yup.ref('allowOther'), 'Must be greater or equal than 0').required(Yup.ref('allowOther'), "arrayNumbers are required"),