Validate fields conditionally based on another field in Yup and Formik

后端 未结 1 1671
再見小時候
再見小時候 2021-01-29 13:40

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

相关标签:
1条回答
  • 2021-01-29 14:19

    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.

    0 讨论(0)
提交回复
热议问题