【问题标题】:Formik & Yup form validation with array using yupFormik & Yup 使用 yup 对数组进行表单验证
【发布时间】:2020-03-05 17:04:12
【问题描述】:

我有一个使用 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 数组中所有counts 的总和必须匹配total

【问题讨论】:

    标签: javascript forms validation formik yup


    【解决方案1】:

    你只需要使用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 } 显示错误。

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 2019-09-12
      • 2019-12-26
      • 2019-09-29
      • 2020-05-10
      • 2019-10-09
      相关资源
      最近更新 更多