【问题标题】:Check if event is in future - Yup validation检查事件是否在未来 - 是的验证
【发布时间】:2021-10-18 00:12:50
【问题描述】:

我目前正在为项目中的一个页面进行 yup 验证。我坚持以下几点: 用户选择事件的日期、时区和具体时间(他可以选择每十五分钟从 00:00 到 23:45 的时间)。现在,我需要验证选择的时间是否在未来。我真的很困惑:我应该首先将当前时刻转换为用户选择的时区,还是将用户的时刻转换为本地时区,或者其他什么。 当我对时区不小心时,这是我首先做的:

[keys.startTime]: yup
      .number()
      .required(errors.required)
      .when(['date'], (date, schema: any) => {
        const currentTimeInMinutes = moment().hours() * 60 + moment().minutes()
        if (
          moment(date).date() === moment().date() &&
          moment(date).month() === moment().month() &&
          moment(date).year() === moment().year()
        )
          return schema.min(currentTimeInMinutes, errors.pastTime)
      }),

但后来我意识到我没有考虑选择的时区。 这里的开始时间表示从 00:00 到所选时间的分钟数,例如如果用户选择 00:15,则 startTime 将为 15。 提前致谢。

【问题讨论】:

    标签: reactjs validation yup


    【解决方案1】:

    您需要比较 - 当前时间(在提交时)与用户选择/输入的datestartTime 都在用户选择的区域

    
    // Calculate the offset of the timezone that user selected from UTC
    const utcOffset = '+05:30'; // Example of a time zone in India
    
    const currentTime = moment().utcOffset(utcOffset);
    const userSelectionTime = 
      moment(date).utcOffset(utcOffset)
        .startOf('day')
        .add(startTime, 'minutes');
    
    /*
     * Check if the difference between the `userSelectionTime` and the `currentTime`
     * is greater than 0 minutes (you can change this as per your requirements)
     */
    const selectionIsValid = userSelectionTime.diff(currentTime, 'minutes') > 0;
    
    

    【讨论】:

    • 非常感谢!由于 typescript + yup 语法,我仍在苦苦挣扎,但至少现在我有办法做到这一点。
    • 嘿,如果这解决了您的问题,请将其标记为答案。
    • 另外,请将您的问题发布在您遇到 TS + yup 语法的地方 - 我也可以帮助您。
    • 另外,我在上面的代码中看到了一些不寻常的地方 - 在 .when 块中,当 if 条件为真但您没有为 falsy 条件返回任何内容时,您返回了 schema.min(...)
    • 是的,我忘了写在其他情况下会发生什么。实际上,我认为只有在日期相同时才需要验证 startTime - 这就是为什么我只包括这种情况。不过,我应该用一些东西写一个 else 声明。现在,关于 TS + yup 语法,我对这个 '.when(['date', 'timeZone'], (date, timeZone, schema: any) => {...}' 有问题似乎我需要提供日期或时区类型,但我没有成功。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    相关资源
    最近更新 更多