使用多个输入作为变量

时间:2020-08-06 17:46:45

标签: reactjs formik yup

使用formik,我想使用多个输入作为变量来创建日期对象。例如,具有一个出生日期表单字段,该字段取决于用户键入的三个输入(年,月,日),并显示错误,如果他们的日期无效(例如2/31/2020),则会提醒他们

const multipleDependentValidation = Yup.object().shape({
  isDay: Yup.boolean(),
  isMonth: Yup.boolean(),
  isYear: Yup.boolean(),
  birthdate: Yup.date().when(['isDay', 'isMonth', 'isYear'], {
    is: (isDay, isMonth, isYear) => {
      return true;
    },
    then: Yup.cast(
      { notThis: [Yup.ref('year')], butThis: [Yup.ref('year').string()] },
      { notThis: [Yup.ref('month')], butThis: [Yup.ref('month').string()] },
      { notThis: [Yup.ref('day')], butThis: [Yup.ref('day').string()] }
    )
      .date()
      .nullable()
      .required(),
  }),
});
multipleDependentValidation
  .validate({ isDay: true, isMonth: true, isYear: true, birthdate: true })
  .then(function (value) {
    console.log(value);
  })
  .catch(function (err) {
    console.log(err);
  });

0 个答案:

没有答案