javascript Nodejs 中的日期验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17433472/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:18:46  来源:igfitidea点击:

Date Validation in Nodejs

javascriptnode.jsvalidationdatemongoose

提问by Saransh Mohapatra

I want the user to input his date of birth. And I would want it be in format YYYY-MM-DD. Node-Validator right now validates all date format, not a particular format. So If I input 12324433 , it is also validated as it thinks its epoch time.

我希望用户输入他的出生日期。我希望它采用 YYYY-MM-DD 格式。节点验证器现在验证所有日期格式,而不是特定格式。所以如果我输入 12324433 ,它也会被验证,因为它认为它的纪元时间。

Please help me out as to what should I do? This question is specific to validation in Mongoose

请帮我看看我该怎么办?此问题特定于 Mongoose 中的验证

回答by David

I'm a big fan of express-form, def worth a look -- you can also use moment.js. I've used it myself a for this very reason

我是 的忠实粉丝express-form,绝对值得一看——你也可以使用moment.js. 出于这个原因,我自己使用了它

from moment.js docs:

来自 moment.js 文档:

moment("2011-10-10", "YYYY-MM-DD").isValid(); // true
moment("2011-10-50", "YYYY-MM-DD").isValid(); // false (bad day of month)

Cheers, I hope this helps :)

干杯,我希望这有帮助:)

ps - moment.js github urljust in case.

ps - moment.js github url以防万一。

回答by Naor Biton

As Node-Validator's documentation points out, "regex is probably a better choice". I whipped up a regex that looks pretty good, and I believe it'll get the job done, but I advise you to test it thoroughly, if you plan to use it.

正如 Node-Validator 的文档所指出的那样,“regex 可能是更好的选择”。我创建了一个看起来不错的正则表达式,我相信它可以完成工作,但我建议你彻底测试它,如果你打算使用它。

/\d\d\d\d-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])/

This regex will validate a date in the format YYYY-MM-DD, that you need. You can see a working code snippet that uses it here: http://tinker.io/c269b/

此正则表达式将验证您需要的格式为 YYYY-MM-DD 的日期。您可以在此处看到使用它的工作代码片段:http: //tinker.io/c269b/

Good luck!

祝你好运!

Edit:I noticed something that breaks it. This regex validates partial matches, so an input like "1970-01-011" checks out as valid. This happens because I forgot to add the startand endmarkers inside the regex. This is how it looks after I fixed it:

编辑:我注意到一些东西打破了它。此正则表达式验证部分匹配,因此像“1970-01-011”这样的输入检查为有效。发生这种情况是因为我忘记在正则表达式中添加开始结束标记。这是我修复后的样子:

/^\d\d\d\d-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/

The example on Tinker is also updated with the fix.

Tinker 上的示例也更新了修复程序。

回答by Raz Weizman

Since I was also looking into this and was checking express validator as well, I mocked up a regex as well that might help you out with validating dates.

因为我也在研究这个并且也在检查快速验证器,所以我模拟了一个正则表达式,它可能会帮助你验证日期。

((19|2\d)\d\d)-((0?[1-9])|(1[0-2]))-((0?[1-9])|([12]\d)|(3[01]))

Here is an image that explains it:

这是解释它的图像:

enter image description here

在此处输入图片说明