Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a date is valid

Short answer

An invalid date has NaN inside. Check it with getTime():

const isValidDate = (date) => !Number.isNaN(date.getTime());
 
console.log(isValidDate(new Date('2025-06-15T10:00')));
console.log(isValidDate(new Date('hello')));

Output:

true
false

A string like YYYY-MM-DD

new Date() quietly moves February 30 to March. Build the date from the parts and check that they did not change:

const isValidYmd = (value) => {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
  if (!match) return false;
  const [year, month, day] = match.slice(1).map(Number);
  const date = new Date(year, month - 1, day);
  return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
};
 
console.log(isValidYmd('2024-02-29'));
console.log(isValidYmd('2025-02-29'));
console.log(isValidYmd('2025-13-01'));
console.log(isValidYmd('15.06.2025'));

Output:

true
false
false
false

A date in a range

For a date of birth, also check that it is not in the future:

const birth = new Date(2090, 0, 1);
 
console.log(birth <= new Date() ? 'ok' : 'a date in the future');

Output:

a date in the future

Common mistake

The Date constructor does not report wrong days, it rolls them over:

console.log(new Date(2025, 1, 30).toDateString());

Output:

Sun Mar 02 2025

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.