- Instant help with your JavaScript coding problems

Check if date is valid in JavaScript

Question:
How to check if date is valid in JavaScript?
Answer:
const dateStr = '2021-11-01';
if (Date.parse(dateStr)) {
    console.log('valid date');
}
Description:

Maybe the simplest way to check if a date is valid in JavaScript is using the parse method of the Date object. In case of a valid date, it returns the timestamp of the date and NaN otherwise. So it will not throw an error in case of invalid date inputs.

const dateStr = '2021-14-01';
if (Date.parse(true)) {
    console.log('Valid date');
} else {
    console.log('Invalid date');
}
Share "How to check if date is valid in JavaScript?"