Skip to content
Advertisement

DayJS isValid behaves differently to Moment

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement