Date Validation in Nodejs Date Validation in Nodejs mongoose mongoose

Date Validation in Nodejs


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

from moment.js docs:

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

Cheers, I hope this helps :)

ps - moment.js github url just in case.


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.

/\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/

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 start and end markers inside the regex. This is how it looks after I fixed it:

/^\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.


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