【问题标题】:Yup: How to validate two dates which are dependent on each other?是的:如何验证两个相互依赖的日期?
【发布时间】:2020-01-18 23:32:10
【问题描述】:

我正在使用 Formikyup 进行验证。
我对startedended 两个字段的验证有以下要求

  1. started 必须是有效日期。
  2. started 必须是过去的日期。
  3. ended 可以为空,表示不需要。
  4. ended 不能为空,并且必须是有效日期,如果 started 具有有效的日期值。

这是我的验证模式:

validationSchema={yup.object().shape({
    started: yup.date().max(new Date(), "Future date not allowed").typeError("Invalid Started date"),
    ended: yup.date().default(null).when("started", {
        is: yup.date().isValid(),
        then: yup.date().min(yup.ref("started"), "Ended date must be later than Start date"),
        otherwise: yup.date().nullable()
    }).typeError("Invalid Ended date")
})}

1,2,3 有效,但第 4 次验证无效。
我还尝试将其更改为is: started => started !==null,这是完全错误的,因为我console.log(started) 并打印了我Invalid date
我什至尝试过is: true,但也没有用。

验证此要求的正确方法是什么?

【问题讨论】:

    标签: formik yup


    【解决方案1】:

    从这里得到这个解决方案https://stackoverflow.com/a/60277510

    但基本上这将检查开始是否存在,然后检查结束时间是否更晚:

     ended: yup.date().default(null)
                    .when("started",
                        (started, yup) => started && yup.min(started, "End time cannot be before start time"))
    

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 2017-06-27
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      相关资源
      最近更新 更多