Home > Net >  Formik Yup - How to validate the value of the input itself with another one?
Formik Yup - How to validate the value of the input itself with another one?

Time:11-28

I would like to do the following validation:

  • If it was necessary to inform a coupon, the error message would appear, but even with the following code this is not possible.
import * as yup from 'yup';

export type FormValues = {
  promotionalCode: string;
  requirePromotionalCode: boolean;
};

export const validationSchema = yup.object().shape({
  requirePromotionalCode: yup.boolean(),
  promotionalCode: yup.string().when('requirePromotionalCode', {
    is: true,
    then: yup.string().required('Please, enter a coupon'),
    otherwise: yup.string().notRequired(),
  }),
});

I tried as follows, but nothing worked.

import * as yup from 'yup';

export type FormValues = {
  promotionalCode: string;
  requirePromotionalCode: boolean;
};

export const validationSchema = yup.object().shape({
  requirePromotionalCode: yup.boolean(),
  promotionalCode: yup.string().when('requirePromotionalCode', {
    is: (requirePromotionalCode, promotionalCode) =>
      requirePromotionalCode && !promotionalCode,
    then: yup.string().required('Please, enter a coupon'),
    otherwise: yup.string().notRequired(),
  }),
});

CodePudding user response:

To make Yup.when work properly, you would have to add promotionalCode and and requirePromotionalCode to initialValues and to your Yup schema shape.

In general, when using validationSchema, it is best practices to ensure that all of you form's fields have initial values so that Yup can see them immediately.

The result would look like:

<Formik initialValues={{ promotionalCode : '', requirePromotionalCode: false }} validationSchema={Yup.object().shape({ ...

CodePudding user response:

In many cases .test() would work (read the docs here).

This is the example to solve the problem:

import * as yup from 'yup';

export type FormValues = {
  promotionalCode: string;
  requirePromotionalCode: boolean;
};

export const validationSchema = yup.object().shape({
  requirePromotionalCode: yup.boolean(),
  promotionalCode: yup.string().test(
    'requirePromotionalCode',
    'Please, enter a coupon',
    (value, context) => context.requirePromotionalCode && !!value
  ),
});

Things to note, .test() expects the value true to pass the 'test', so the return value should be true when the requirePromotionalCode is true and promotionalCode value is not empty.

Otherwise, the error message in the second argument would be thrown.

Hope it helps!

  • Related