JavaScript provides several ways to validate whether a given date is valid. The appropriate approach depends on whether you need to validate the date object itself, a specific date format, or both.
- Check the date using getTime() and isNaN().
- Use a custom validation method to verify the date and its format.
- Use regular expressions when the input must follow a specific date format.
Approach 1: Using isNaN() and getTime()
The getTime() method returns the timestamp of a Date object. For an invalid date, it returns NaN. The isNaN() method can be used to determine whether the date is invalid.
Example: Checks whether a given date is valid using getTime() and isNaN().
function isValidDate(date) {
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(date);
Output
Invalid Date
Approach 2: Using a Custom Method
A custom method can validate a date by checking whether its timestamp is valid and comparing the original date string with the normalized date representation. This helps ensure that the input represents the expected date.
Example: Validates a date string using a custom method.
Date.prototype.isValid = function(dateString) {
return !isNaN(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
Approach 3: Using Regular Expressions
Regular expressions can be used to first verify that a date follows a specific format. After extracting the year, month, and day, a Date object can be created and compared with the original values to ensure that the date itself is valid.
Example: Validates dates in YYYY-MM-DD, DD/MM/YYYY, and MM-DD-YYYY formats.
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;
}
// Check whether the format is correct
if (!regex.test(dateString)) {
return false;
}
// Parse date parts based on the format
let day, month, year;
switch (format) {
case 'YYYY-MM-DD':
[year, month, day] =
dateString.split('-').map(Number);
break;
case 'DD/MM/YYYY':
[day, month, year] =
dateString.split('/').map(Number);
break;
case 'MM-DD-YYYY':
[month, day, year] =
dateString.split('-').map(Number);
break;
}
// Create a Date object
const date = new Date(year, month - 1, day);
// Validate the date parts
return date.getFullYear() === year &&
date.getMonth() === month - 1 &&
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