使用 momentjs 进行时间验证

Time validation with momentjs

我正在尝试根据用户输入进行时间计算。在启动计算之前,我使用 momentjs 来验证用户时间输入。它似乎表现得很奇怪。例如,这里是浏览器控制台中未定义的输入:

>moment(undefined).isValid()
>true

如何使用 momentjs 验证用户输入?

编辑:

似乎在严格模式下您可以验证除带有时区缩写 (EEST) 的日期以外的所有内容:

Tue May 05 2015 12:00:00 GMT+0300 (EEST)

由于浏览器不兼容,用于缩写的 z 参数已弃用:https://github.com/moment/moment/issues/162

如果你限制输入日期的模式 - 你必须使用这样的东西:

checksDate = moment(date, ['DD-MMMM-YYYY', 'DD.MM.YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD'], true);

这个数组在哪里:

['DD-MMMM-YYYY', 'DD.MM.YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD']

是你的模式。 我的 moment 语句中的第三个参数定义 moment.js 必须使用严格模式。这意味着你不能使用“。”而不是 ISO 格式中的“-”:例如“1990-09-01”。 在文档中你可以看到这个短语:

Moment's parser is very forgiving, and this can lead to undesired behavior. As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly.

在浏览器的控制台中:

moment(undefined).isValid()
true
moment(undefined, [], true).isValid()
false

但强烈建议使用我在上面示例中使用的模式。 因为没有它 moment.js 可能会在这个日期上出错: "01.11.2000""11.01.2000" - 可以是相似的日期,然后您使用任意用户输入。

阅读更多: moment.js Docs about validation

我希望,一切都清楚了。