我有一个使用Formik的<Form />和<FieldArray />组件的动态表单。我的验证模式如下:
const countPerKgSchema = total => {
return Yup.object().shape({
rows: Yup.array()
.of(
Yup.object().shape({
count: Yup.string().required('Count is required'),
kg: Yup.string().required('Weight is required.'),
})
)
.required()
.min(1, `Provide at least 1 row`),
saleIds: Yup.array()
.of(Yup.number)
.required(),
});
};如何添加验证规则,即rows数组中所有count的和必须与total匹配
发布于 2020-11-30 03:58:48
你只需要使用Yup的test()方法来验证总数:
object().shape({
rows: array()
.of(...)
.required()
.test(
'sum',
'The total number of elements must match the total.',
(rows = []) => {
const total = rows.reduce((total, row) => {
return total + (row.count|| 0);
}, 0);
return total <= XYZ;
}
)
})如果验证失败,errors对象将如下所示:
{
"rows": {
"message": "The total number of elements must match the total.",
"type": "sum"
}
}然后,您可以使用{ errors.rows?.message }显示错误。
https://stackoverflow.com/questions/60550590
复制相似问题