我有一个使用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
匹配?
您只需要使用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 }
显示错误。