Date Validation in Nodejs

20,491

Solution 1

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(); // true
moment("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.

Solution 2

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.

Solution 3

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

Share:
20,491
Saransh Mohapatra
Author by

Saransh Mohapatra

Updated on November 12, 2021

Comments

  • Saransh Mohapatra
    Saransh Mohapatra over 2 years

    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.

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