Published on: 18 Oct, 2019

How to check if a date is valid in JavaScript?

Tumblr Digg Google Plus

In this article, we are going to learn how to check if a variable date is a valid date or not in Javascript. To make it easier, we are going to create a simple function that will accept one parameter and will return a boolean value. If it is a valid date, it will return a true value otherwise it will return a false value.

We are going to use the built in getFullYear extension under the Javascript Date object. If it is a correct date. It will return a number. Therefore we are going to use isNaN to check if it is a valid number.

Here is our JavaScript function code.

validDate = function (value) {
	if (value === null) { return false; }
	var d = new Date(value);
	return !isNaN(d.getFullYear());

Here is the example of how to use above method.

console.log("3 Feb 2019 :", validDate("3 Feb 2019"));
console.log("30/01/2019 :", validDate("30/01/2019"));
console.log("01/30/2019 :", validDate("01/30/2019"));
console.log("2019-30-1 :", validDate("2019-30-1"));
console.log("2019-1-30 :", validDate("2019-1-30"));
console.log("abcdef: ", validDate("abcdef"));
console.log("a123abc: ", validDate('a123abc'));

Check our other Javascript articles in here.

Quick Demo in Codepen

You can view the quick demo on the following link.


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.