【问题标题】:How to check date format validation with moment如何使用时刻检查日期格式验证
【发布时间】:2020-02-08 10:11:10
【问题描述】:

我的问题是关于输入日期格式的验证。我想要true 当且仅当日期完全以这种格式输入时,MM-DD-YYYY。但我的代码也只是用 / (即用斜杠)验证日期。这意味着02-29/202001/30-2020 甚至像02/-29-/2020 这样的混合格式也是true。此外,日、月和年必须分别采用 2 位和 4 位格式。我得到了帮助: moment to validate date and time with custom format。我还创建了一个stackblitz。这是我的代码:

validate(sDate: string, eDate: string) {
  this.isValidDate = true;
  this.startInvalid = false;
  this.endInvalid = false;
  this.dateErrors = new Set<string>();
  const fromDate = moment(sDate, "MM-DD-YYYY");
  console.log(fromDate.isValid());
  const toDate = moment(eDate, "MM-DD-YYYY");
  const currentDate = moment();
  if (fromDate.isAfter(toDate)) {
      this.dateErrors.add('Errors.StartDateMoreThanEndDate');
      this.startInvalid = true;
      this.isValidDate = false;
  }
    console.log(this.dateErrors);
    return this.isValidDate;
}

这是否可能在瞬间实现,或者我将不得不为此编写一些正则表达式。如果我第一次使用 moment 时我的整个实现是错误的,我很抱歉。

【问题讨论】:

    标签: typescript momentjs


    【解决方案1】:

    你可以用下面这句话

    moment(someDate, 'MM-DD-YYYY', true).isValid()

    它将返回一个布尔值

    【讨论】:

    • 此解决方案有效。这么晚才回复很抱歉。你能解释一下为什么我的代码不起作用。
    【解决方案2】:

    我相信当你构造 moment 时,你会写这样的东西:

    const myDate = moment(strDate, "MM-DD-YYYY", true)
    

    最后一个变量将 strict parsing 设置为 true(请参阅此处的文档:https://momentjs.com/docs/#/parsing/

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多