首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Yup对数组进行Formik & yup表单验证

使用Yup对数组进行Formik & yup表单验证
EN

Stack Overflow用户
提问于 2020-03-06 01:04:13
回答 1查看 622关注 0票数 2

我有一个使用Formik的<Form /><FieldArray />组件的动态表单。我的验证模式如下:

代码语言:javascript
复制
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匹配

EN

回答 1

Stack Overflow用户

发布于 2020-11-30 03:58:48

你只需要使用Yup的test()方法来验证总数:

代码语言:javascript
复制
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对象将如下所示:

代码语言:javascript
复制
{
  "rows": {
    "message": "The total number of elements must match the total.",
    "type": "sum"
  }
}

然后,您可以使用{ errors.rows?.message }显示错误。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60550590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档