【发布时间】:2020-02-08 10:11:10
【问题描述】:
我的问题是关于输入日期格式的验证。我想要true 当且仅当日期完全以这种格式输入时,MM-DD-YYYY。但我的代码也只是用 / (即用斜杠)验证日期。这意味着02-29/2020、01/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