根据 Yup 和 Formik 中的另一个字段有条件地验证字段

Validate fields conditionally based on another field in Yup and Formik

我在验证时遇到问题。我想如果 access 值为 1 那么你可以 select start_dateend_date 但是如果 access 的值不是 1,那么你只能select今天。

Codesandbox

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

您可以使用日期验证来代替字符串验证,只需确保设置正确的消息!:

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

可以找到更新 stackblitz here