dayjs: Validation .isValid() doesn't work always

The .isValid() validation doesn’t function correctly under the following condition:

  • When the the day part is 31 for a month which didn’t have 31 days.

Some instances where .isValid() returns true for a date that is invalid:

  • dayjs().isValid('1995-02-31')
  • dayjs().isValid('1995-03-31')
  • dayjs().isValid('1995-04-31')
  • dayjs().isValid('1995-06-31')
  • dayjs().isValid('1995-09-31')
  • dayjs().isValid('1995-11-31')

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 9
  • Comments: 18 (2 by maintainers)

Most upvoted comments

Is this an option to validate if date exist?

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

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

Why is this still closed? This issue cost me at least 4 hours because it is still broken.

@mateuszpigula passing a third parameter true is checking if the date actually exists, unlike the native Date implementation.

dayjs("2021-15-35", "YYYY-MM-DD").isValid();         //true
dayjs("2021-15-35", "YYYY-MM-DD", true).isValid();   //false

I’ve tested a few cases including leap years, and this seems to work fine to check if the date actually exists.

Turns out dayjs('31/02/2021', 'DD/MM/YYYY', true).isValid() can be used to check if passed date exists or not.

But not sure how… could somebody explain ?

facing same issue, isValid() always returns true

const dayjs = require("dayjs")
console.log(dayjs('2021-15-35').isValid())
const dayjs = require("dayjs")

console.log(dayjs('2021-15-35', 'YYYY-MM-DD').isValid())

Expected: false Received: true

Any suggestion?

Moreover, isValid doesn’t validate if passed date is exists, it’s just validate that date was parsed correctly. So, if you pass dayjs('2018-11-41').isValid() the date will be parsed as 2018-12-10 and isValid will return true anyway

Why does dayjs require a special plugin just to validate if a month has a 31st day?

This is the very first thing I’ve tried with Day.js and it’s failed. I’ve installed the customParseFormat module too (and I’ve done the extend). console.log(dayjs("31-11-2022", "DD-MM-YYYY").isValid()); gives true.

That’s still validating as true for me too