DayJS isValid behaves differently to Moment

Viewed 9763

I was trying to validate birthday using dayjs but its isValid is returning true for a date that doesn't exist. Funnily enough, the isValid by moment is working just fine.

dayjs('2019/02/31', 'YYYY/MM/DD').isValid() // true
moment('2019/02/31', 'YYYY/MM/DD').isValid() // false

I can't switch to moment because of the lightweightness of dayjs

Any idea how to tackle this?

5 Answers

August 2021: It's now possible to detect with .isValid() method these invalid dates passing a third parameter as true to dayjs constructor:

dayjs('2019/02/31', 'YYYY/MM/DD').isValid() // true
dayjs('2019/02/31', 'YYYY/MM/DD',true).isValid() // false

More information on this strict parsing argument can be found now at official doc.

NOTE: In Node.js I had to load first customParseFormat plugin before calling isValid() to receive expected validity results:

const dayjs = require("dayjs");
var customParseFormat = require("dayjs/plugin/customParseFormat");
dayjs.extend(customParseFormat);

Please look at this thread. Basically isValid doesn't validate if passed date is exists, it just validates that date was parsed correctly.

I'm not exactly sure if this works in all scenarios (especially if you have localization), but you could try something like:

function validate(date, format) {
  return dayjs(date, format).format(format) === date;
}

validate('2019/02/31', 'YYYY/MM/DD') // false

Reason for this kind of check is that

dayjs('2019/02/31', 'YYYY/MM/DD').format('YYYY/MM/DD')

returns 2019/03/03. Then when you compare it to your initial date (you should be able because formatting is the same) you should get the same value - and in this case you don't.

How moment.isValid() works (overflow checks)

If the moment that results from the parsed input does not exist, moment#isValid will return false.

How dayjs.isValid() works

If you look at the source code:

src/index.js

this.$d = parseDate(cfg) // Line 75
// ...
isValid() { // Line 96
  return !(this.$d.toString() === C.INVALID_DATE_STRING)
}

src/constant.js

export const INVALID_DATE_STRING = 'Invalid Date'

If you look to the source parse is not a straighforward Date.parse() because it take in consideration locale, date format and so on, but it seems that every valid date passed to Date() or Date.parse() are valid.

Date.parse('2019/02/31') // 1551567600000
new Date(2019/02/31) // Thu Jan 01 1970 01:00:00 GMT+0100

use strict mode

dayjs('2019/02/31', 'YYYY/MM/DD', true).isValid() //false

enter image description here

When strict mode is not enforced enter image description here

Note: you have to extend customParseFormat plugin as a prerequisite

You can use customParseFormat plugin from day.js I do this on my react project and this is work perfectly fine.

import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

dayjs.extend(customParseFormat);

dayjs('30-02-2022', 'DD-MM-YYYY', true).isValid() // false

Related