Yup conditional validation

Viewed 4252

I want to validate one field on the basis of other using my schema. Like, if carType is "SUV" maximum "noOfPassengers" should be 6 else 4. But, it's not validating this case, neither I can debug this nor getting any error in console.

const validationSchema = yup.object().shape({
    location: yup
        .string()
        .required('location is required'),
    destination: yup
        .string()
        .required('Destination is required'),
    carType: yup
        .string(),
    noOfPassengers: yup
        .string()
        .when('carType', {
            is: value => value && value === "SUV",
            then: yup
                .string()
                .max(6, 'Max 6 passengers are required'),
            otherwise: yup
                .string()
                .max(4, 'Max 4 passengers are required'),
        }),
});
1 Answers

You are comparing the values of noOfPassengers as string while it should be a number something like this:

Yup.object().shape({
  location: Yup
      .string()
      .required('location is required'),
  destination: Yup
      .string()
      .required('Destination is required'),
  carType: Yup
      .string(),
  noOfPassengers: Yup
      .number()
      .when('carType', {
          is: value => value && value === "SUV",
          then: Yup
              .number()
              .max(6, 'Max 6 passengers are required'),
          otherwise: Yup
              .number()
              .max(4, 'Max 4 passengers are required'),
      }),
});

If you run this you should get validation error. You have a flaw in logical condition as well. You should fix that too but that isn't the scope of this answer.

The problem is

Yup.string() should be Yup.number() because you are then comparing it in max.

Related