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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With