Validate a date in Nodejs with MomentJs

综合编程 2018-06-25 阅读原文

I want to validate a date in a NodeJS application.

I tried the MomentsJs
library, but it seems that the isValid()
function ignored all alpha characters, it's too tolerant for me (When I specify the dateformat as YYYY-MM-DD
, I expect that the date is a 10-characters-string.):

moment("One,2 and 011, 12-10", "YYYY-MM-DD").isValid()  // returns true instead of false
moment("Seppl"); // parsing seems to work with all values?

Is there any way to check dates more strictly?

How can I check if parsing a date fails? (It returns -62167222800000
when printing wrong dates it).

Is there any other better Javascript Data lib that work with different date formats and support date manipulations like MomentJs?

Problem courtesy of: Sonson123


Moment.js library doesnt provide any method validate the date with given format.

moment("", dateFormat) will just check the given date but not with given format.

Following lines from

Note: It is not intended to be used to validate that the input string matches the format string. Because the strictness of format matching can vary depending on the application and business requirements, this sort of validation is not included in Moment.js.

Solution courtesy of: Kiran Nunna

Node.js Recipes

责编内容by:Node.js Recipes阅读原文】。感谢您的支持!


Node.js My Request is Not Blocking I'm new to node.js , and I'm trying to call a service, parse its data and return it as part of a view. I can't see...
http.clientResponse – Way to get ‘reas... Node.js Recipes are structured in a Cookbook format featuring recipes that contain problem statements and solution...
Mongoose For Node.js error object has no method va... I Am making a blog with node/express/mongoose and I keep getting this error: /Users/Ari/Sites/Amateur Dev/node_modu...
Node.js v8 Gets Long-Term Support — Plus a Commitm... JavaScript developers worldwide are getting a sweet treat this Hallowe’en:Node.js, the planet’s favorite open source Ja...
What is Pug.js (Jade) and How can we use it within... This quick tutorial will guide you through what Pug.js is, and how to use it with Node & Express in a real-world ...