How to check a date is valid or not using JavaScript?
To check if a date is valid or not in JavaScript, we have to know all the valid formats of the date. For ex - "YYYY/DD/MM", "DD/MM/YYYY", and "YYYY-MM-DD", etc. We have a given date format and we need to check whether the given format is valid or not according to the official and acceptable date format.
Using Custom Method
The custom method validates a date by creating a Date object and comparing getTime() method to itself. A valid date returns a value, while an invalid date returns NaN, which isn't equal to itself, indicating an invalid date.
Date.prototype.isValid = function (dateString) {
// Compare the original date string with the date object
return this.getTime() === this.getTime() && dateString === this.toISOString().slice(0, 10);
};
const dateString = "2012/2/30";
const date = new Date(dateString);
console.log(date.isValid(dateString));
Output
false
Using isNan() Method
The isNaN() method checks if the getTime() method of a Date object returns NaN. A valid date will return a number, while an invalid date will return NaN, which is identified using the isNaN() function.
function isValidDate() {
if (Object.prototype.toString.call(date) === "[object Date]") {
if (isNaN(date.getTime())) {
console.log("Invalid Date");
}
else {
console.log("Valid Date");
}
}
}
// Driver code
const date = new Date("This is not date.");
isValidDate();
Output
Invalid Date
Using Regular Expressions
The Regular Expressions validates a date by first matching the input against a defined regex pattern for specific formats. It then checks if the resulting Date object is valid using getTime().
function isValidDateFormat(dateString, format) {
let regex;
// Define regex patterns for different date formats
switch (format) {
case 'YYYY-MM-DD':
regex = /^\d{4}-\d{2}-\d{2}$/;
break;
case 'DD/MM/YYYY':
regex = /^\d{2}\/\d{2}\/\d{4}$/;
break;
case 'MM-DD-YYYY':
regex = /^\d{2}-\d{2}-\d{4}$/;
break;
default:
return false; // Unsupported format
}
// Check if dateString matches the regex
if (!regex.test(dateString)) return false;
// Parse date parts based on the format
let parts, day, month, year;
switch (format) {
case 'YYYY-MM-DD':
[year, month, day] = dateString.split('-').map(Number);
month--; // JS months are 0-based
break;
case 'DD/MM/YYYY':
[day, month, year] = dateString.split('/').map(Number);
month--;
break;
case 'MM-DD-YYYY':
[month, day, year] = dateString.split('-').map(Number);
month--;
break;
}
// Create a Date object and validate
const date = new Date(year, month, day);
return date.getFullYear() === year &&
date.getMonth() === month &&
date.getDate() === day;
}
// Driver code
console.log(isValidDateFormat('2024-05-24', 'YYYY-MM-DD'));
console.log(isValidDateFormat('24/05/2024', 'DD/MM/YYYY'));
console.log(isValidDateFormat('05-24-2024', 'MM-DD-YYYY'));
console.log(isValidDateFormat('2024/05/24', 'YYYY-MM-DD'));
Output
true true true false
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.