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

Solution

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 momentjs.com

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.

http://momentjs.com/docs/#/parsing/is-valid/

Solution courtesy of: Kiran Nunna

Node.js Recipes

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

您可能感兴趣的

Why Nodejs serves a file with 80x more CPU usage t... Take the same code that sits on nodejs.org home page. Serve a static file that is 1.8Mb. And do the same with Nginx, and watch the difference. ...
Dynamic queries in MongoDB and Node.js I am working on a nodejs/express app with Mongodb on the backend. In one of my API calls, depending on the presence of a particular querystring parame...
阿里企业级 Node.js 框架 Egg 2.1.0 发布,常规更新... 阿里企业级 Node.js 框架 Egg 2.0 已于前两周发布,包含重大的更新。昨日,发布了 Egg 2.1.0,更新如下: 值得关注的变化 新特性 为损坏的客户端请求添加了 400 响应,以代替之前的空响应 dump application router js...
开源书籍-Node.js实践 《Node.js实践 》(Practical Node.js) 是由Azat Mardan编写的关于Node.js的技术书籍。第一版由 出版社: Apress出版,作者把第二版发布在Github上并进行了开源,预计2017年底完稿,读者即可购买纸质版。 Azat 是开源 Node.js...
Restart Your Node.js Apps Automatically Using node... So you’re working on a Node.js application and getting awfully tired of restarting the process every time you make a change? Enter nodemon , a CLI...