Search⌘ K
AI Features

Solution Review: Validate the Date

Explore how to validate date strings in JavaScript by creating date objects and verifying their validity with built-in methods. This lesson helps you understand checking both the date type and the time to ensure correct date input.

We'll cover the following...

Solution

Javascript (babel-node)
const isValidDate = dateString => {
const date = new Date(dateString);
if (
Object.prototype.toString.call(date) === "[object Date]" &&
!isNaN(date.getTime())
) {
return true;
} else {
return false;
}
};
console.log(isValidDate("foo"));
console.log(isValidDate("October 30, 2019"));
console.log(isValidDate("May 8, 2016 10:12:00"));
console.log(isValidDate("April 15, 2012 11:xyz"));

Explanation

...