jQuery moment.js isValid 函数无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19978953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
moment.js isValid function not working properly
提问by Mikel Sanchez
I have this question... I haven't found anything similar and it also seems very strange that nobody had this problem validating time with moment.js.
我有这个问题......我没有发现任何类似的东西,而且没有人在使用 moment.js 验证时间时遇到这个问题似乎也很奇怪。
moment('03:55', 'HH:mm').isValid(); //true
moment('03:55jojojo', 'HH:mm').isValid(); //true
moment('03:55jojojo', 'HH:mm',true).isValid(); //true
Am I doing something wrong? Here is an example:
难道我做错了什么?下面是一个例子:
回答by Jan Sommer
In your question you write that moment('03:55jojojo', 'HH:mm',true).isValid();
returns true. This is incorrect. Please check your jsfiddle again.
在您的问题中,您写道moment('03:55jojojo', 'HH:mm',true).isValid();
返回 true。这是不正确的。请再次检查您的 jsfiddle。
From http://momentjs.com/docs/
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 的解析器非常宽容,这可能会导致不受欢迎的行为。从 2.3.0 版本开始,您可以为最后一个参数指定一个布尔值,以使 Moment 使用严格解析。严格解析要求格式和输入完全匹配。
moment('It is 2012-05-25', 'YYYY-MM-DD').isValid(); // true
moment('It is 2012-05-25', 'YYYY-MM-DD', true).isValid(); // false
moment('2012-05-25', 'YYYY-MM-DD', true).isValid(); // true
You can use both language and strictness.
您可以同时使用语言和严格性。
moment('2012-10-14', 'YYYY-MM-DD', 'fr', true);
回答by knnhcn
Sorry to necro this 5 year old question, but I indeed stumbled upon a case where monent is not working properly towards the documentation, using version 2.24.0.
很抱歉解决这个 5 年前的问题,但我确实偶然发现了使用 2.24.0 版 monent 无法正常处理文档的情况。
In the picture we can see that for example H
should only evaluate to 0 - 23
, but if I use moment('01', 'H', true).isValid()
I still get true
.
在图片中我们可以看到,例如H
应该只评估为0 - 23
,但如果我使用moment('01', 'H', true).isValid()
我仍然得到true
.
Here is the jsfiddle: https://jsfiddle.net/wofgst5v/
这是 jsfiddle:https://jsfiddle.net/wofgst5v/