首页 > 解决方案 > 如何使用时刻检查日期格式验证

问题描述

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

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

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

标签: typescriptmomentjs

解决方案


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

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

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


推荐阅读