Validate fields conditionally based on another field in Yup and Formik

5.2k views Asked by At

I have a problem in validation. I wanted that if access value is 1 then you can select the start_date and end_date BUT if the value of access is not 1, then you can only select today.

Codesandbox

Edit 63973773/error-when-setting-an-input-in-reactjs-label-is-over-overwrites-the-value-of (forked)

export const validationSchema = yup.object().shape({
  access: yup.number().nullable(),
  start_date: yup.string().required('Select start date'),
  end_date: yup.string().required('Select end date'),
});
1

There are 1 answers

1
Dipen Shah On BEST ANSWER

Instead of string validation you can use date validation, just make sure to set correct messaging!:

import moment from "moment";
...
const today = new Date().toDateString();
const validationSchema = yup.object().shape({
  access: yup.number().nullable(),
  start_date: yup.date()
    .typeError("Invalid date")
    .required("Select start date")
    .when("access", {
      is: 1,
      otherwise: (d) => d.min(today, "Should be today's date")
          .max(today, "Should be today's date")
    }),
  end_date: yup.date()
    .typeError("Invalid date")
    .required("Select end date")
    .when("access", {
      is: 1,
      otherwise: (d) => d.min(today, "Should be today's date")
          .max(today, "Should be today's date")
    })
});

Update stackblitz can be found here.