Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DayJS isValid behaves differently to Moment

Tags:

javascript

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?

like image 864
Kelok Chan Avatar asked Oct 03 '19 09:10

Kelok Chan


2 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);
like image 55
blert Avatar answered Sep 20 '22 05:09

blert


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.

like image 20
zhuber Avatar answered Sep 19 '22 05:09

zhuber