Saransh Mohapatra
Saransh Mohapatra

Reputation: 9636

Date Validation in Nodejs

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

Upvotes: 6

Views: 26172

Answers (4)

Abhayjeet
Abhayjeet

Reputation: 1

//let pdateFormat = "YYYYMMDDHHmmss";
//let pdateStr = "20210228005959";

let pdateFormat = 'YYYYMMDDHH:mm';
let pdateStr = '2021022823:59';

validateDateFormat (pdateFormat, pdateStr);

function validateDateFormat(dateFormat, dateStr) {
  if (dateFormat.length != dateStr.length) {
    return false;
  }

  let dateIdentifierArr = {
    year: 'YYYY',
    month: 'MM',
    date: 'DD',
    hour: 'HH',
    minute: 'mm',
    second: 'ss',
  };

  let dateConstructVar = {};
  for (var key in dateIdentifierArr) {
    if (dateFormat.indexOf(dateIdentifierArr[key]) != -1) {
      let index = dateFormat.indexOf(dateIdentifierArr[key]);
      dateConstructVar[key] = dateStr.substring(
        index,
        index + dateIdentifierArr[key].length
      );
    } else {
      dateConstructVar[key] = '00';
    }
  }

  let newDate = new Date(
    +dateConstructVar['year'],
    dateConstructVar['month'] - 1,
    +dateConstructVar['date'],
    dateConstructVar['hour'],
    dateConstructVar['minute'],
    dateConstructVar['second']
  );
  if (
    dateConstructVar['year'] != newDate.getFullYear() ||
    dateConstructVar['month'] != ('0' + (newDate.getMonth() + 1)).slice(-2) ||
    dateConstructVar['date'] != ('0' + newDate.getDate()).slice(-2) ||
    dateConstructVar['hour'] != ('0' + newDate.getHours()).slice(-2) ||
    dateConstructVar['minute'] != ('0' + newDate.getMinutes()).slice(-2) ||
    dateConstructVar['second'] != ('0' + newDate.getSeconds()).slice(-2)
  ) {
    console.log('Invalid Date');
  }

  console.log(newDate);
}

Upvotes: 0

Raz Weizman
Raz Weizman

Reputation: 89

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

Upvotes: 1

Naor Biton
Naor Biton

Reputation: 952

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.

Upvotes: 3

David
David

Reputation: 317

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.

Upvotes: 15

Related Questions