javascript moment.js 验证无效日期“2013-10-311”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18997388/
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 validating invalid date "2013-10-311"
提问by Graham Charles
Running moment.js, 2.2.1
运行 moment.js, 2.2.1
moment("2010-10-319", ["YYYY-MM-DD"]).isValid()
... returns true
, and the moment object would be set to 31 October 2010. The parser seems to strip extraneous characters of any sort:
... 返回true
,并且 moment 对象将设置为 2010 年 10 月 31 日。解析器似乎去除了任何类型的无关字符:
moment("2010-10-31a", ["YYYY-MM-DD"]).isValid(); // true
Curiouser, if you add additional format choices, then the "stripping" becomes limited to only one character! (Shouldn't the format strings tests be ORed?)
更奇怪的是,如果您添加其他格式选项,那么“剥离”将仅限于一个字符!(不应该对格式字符串测试进行 OR 运算吗?)
moment("2010-10-319", ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"]).isValid(); // true
moment("2010-10-3199", ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"]).isValid(); // false (!!!)
Is this behaviour by design? I'm not getting why.
这是设计使然吗?我不明白为什么。
EDIT: A commenter found another case where extra characters beyond one are, indeed, stripped:
编辑:一位评论者发现了另一种情况,其中超出一个的额外字符确实被剥离了:
moment("2010-10-319qr", ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"]).isValid(); // true (!)
Here is is in action: http://jsfiddle.net/grahampcharles/r42jg/6/(updated with new case)
这是在行动:http: //jsfiddle.net/grahampcharles/r42jg/6/(更新新案例)
采纳答案by squadwuschel
create an Issue on the Git Repository from momentjs https://github.com/moment/moment/the best way to handle this error.
从 momentjs https://github.com/moment/moment/在 Git 存储库上创建一个问题,这是处理此错误的最佳方法。
回答by timrwood
Moment.js version 2.3.0
added strict parsing.
Moment.js 版本2.3.0
添加了严格解析。
moment("2010-10-319", ["YYYY-MM-DD"]).isValid(); // true
moment("2010-10-319", ["YYYY-MM-DD"], true).isValid(); // false
moment("2010-10-31a", ["YYYY-MM-DD"]).isValid(); // true
moment("2010-10-31a", ["YYYY-MM-DD"], true).isValid(); // false
var formats = ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"];
moment("2010-10-319", formats).isValid(); // true
moment("2010-10-3199", formats).isValid(); // false
moment("2010-10-319", formats, true).isValid(); // false
moment("2010-10-3199", formats, true).isValid(); // false
moment("2010-10-319qr", formats).isValid(); // true
moment("2010-10-319qr", formats, true).isValid(); // false
回答by user3856049
If the user is not selecting any date, then it is showing as invalid date. It is wrong, it should show no date or date not selected. To change that in moment.js you can change that to nodate instead of invalid date.
如果用户没有选择任何日期,则显示为无效日期。这是错误的,它应该不显示日期或未选择日期。要在 moment.js 中更改它,您可以将其更改为 nodate 而不是无效日期。