Thursday 5 August 2021

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

I currently have the following Yup validation schema with react-hook-form:

  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),
  });

This works fine. However, the .test validation is attached to a specific field (i.e. externallyPrintedLabelsQty). Is there any way to attach the .test to the form as a whole instead of to a specific field, or test whether at form level the user is selecting more than 2 labels, regardless if they are printed internally or externally?

Thanks in advance for your help.



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

No comments:

Post a Comment