Check if date is a valid one

I just found a really messed up case.

moment('Decimal128', 'YYYY-MM-DD').isValid() // true

How to check if a string is a valid date using Moment, when the date and date format are different

Sorry, but did any of the given solutions on this thread actually answer the question that was asked?

I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.

The following works for me...

const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();

// Note I: `new Date()` circumvents the warning that
//   Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
//   but may not be optimal.

// Note II: passing `true` as third argument to `moment()` enables strict-mode
//   https://momentjs.com/guides/#/parsing/strict-mode/

But honestly, don't understand why moment.isDate()(as documented) only accepts an object. Should also support a string in my opinion.


var date = moment('2016-10-19', 'DD-MM-YYYY', true);

You should add a third argument when invoking moment that enforces strict parsing. Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.


Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.