使用 Yup 和 react-hook-form 在多个字段上进行表单级别的验证

Validation at form level on multiple fields with Yup and react-hook-form

我目前有以下带有 react-hook-form 的 Yup 验证模式:

  const schema = yup.object().shape({
    externallyPrintedLabelsQty: yup
      .number()
      .typeError("Number of Labels (printed outside) must be a number")
      .required()
      .integer()
      .min(0)
      .max(2)
      .test(
        "maxLabels",
        "A maximum of two labels per pack, either printed internally or externally, is allowed.",
        function (value: any) {
          const { internallyPrintedLabelsQty } = this.parent;
          return value + internallyPrintedLabelsQty < 3;
        }
      ),
    internallyPrintedLabelsQty: yup
      .number()
      .typeError("Number of Labels (printed inside) must be a number")
      .required()
      .integer()
      .min(0)
      .max(2),
  });

这很好用。但是,.test 验证附加到特定字段(即 externallyPrintedLabelsQty)。 有什么方法可以将 .test 作为一个整体附加到表单而不是特定字段,或者测试用户是否在表单级别选择了 2 个以上的标签,无论它们是在内部打印还是在外部打印?

在此先感谢您的帮助。

.test也是Yup.object的一个方法。这意味着将 .test 附加到您的 ObjectSchema 就可以了,就像这样:

const schema = yup
    .object()
    .shape({
        externallyPrintedLabelsQty: yup
            .number()
            .typeError('Number of Labels (printed outside) must be a number')
            .required()
            .integer()
            .min(0)
            .max(2),
        internallyPrintedLabelsQty: yup
            .number()
            .typeError('Number of Labels (printed inside) must be a number')
            .required()
            .integer()
            .min(0)
            .max(2),
    })
    .test(
        'maxLabels',
        'A maximum of two labels per pack, either printed internally or externally, is allowed.',
        (value) => {
            const externallyPrintedLabelsQty =
                value?.externallyPrintedLabelsQty ?? 0;
            const internallyPrintedLabelsQty =
                value?.internallyPrintedLabelsQty ?? 0;

            return externallyPrintedLabelsQty + internallyPrintedLabelsQty < 3;
        }
    );