Introduction
There are lots of validation libraries for Date Validation in JavaScript. Most of the time, the Date Validation Library doesn’t support String Value for validation. Bypassing an invalid date string, the Date instance would still be created. For example, if we provide a number like "20192012" as a date in the Date object in JavaScript or provide "2019-22-30", which is also not a valid date, the date instance would still be created.'
Although some do that, they don't have the tightly coupled format as a different separator, like "/" and "-", can be used on the same date. Moreover, it would be best to verify the month, year, and day of a date separately to detect an invalid date; regex only is not enough.
So, I have written down a simple function to validate the Date. The following example is being used specifically for the "MM/DD/YYYY" format, which can be easily modified.
We will go through the code and understand where we want to change if we want to change the format.
Validation Function
function validatedate(dateString){
let dateformat = /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01])[\/]\d{4}$/;
// Match the date format through regular expression
if(dateString.match(dateformat)){
let operator = dateString.split('/');
// Extract the string into month, date and year
let datepart = [];
if (operator.length>1){
pdatepart = dateString.split('/');
}
let month= parseInt(datepart[0]);
let day = parseInt(datepart[1]);
let year = parseInt(datepart[2]);
// Create list of days of a month
let ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if (month==1 || month>2){
if (day>ListofDays[month-1]){
///This check is for Confirming that the date is not out of its range
return false;
}
}else if (month==2){
let leapYear = false;
if ( (!(year % 4) && year % 100) || !(year % 400)) {
leapYear = true;
}
if ((leapYear == false) && (day>=29)){
return false;
}else
if ((leapYear==true) && (day>29)){
console.log('Invalid date format!');
return false;
}
}
}else{
console.log("Invalid date format!");
return false;
}
return true;
}
In the above "validatedate" function, we can pass a Date String in "MM/DD/YYYY" format. The function implementation is given below,
var a = validatedate("06/16/2019");
console.log(a);
This also validates the "M/D/YYYY", "M/DD/YYYY", and "MM/D/YYYY" formats.
The function will return true if the date is valid in the expected format. Otherwise, it will return false. The function will check the date range where '04/31/2019' is the wrong date while it validates the date format. But "MM=04" means the month is April which ends in 30 Days. So "DD=31" is a faulty date. And this function will also check the leap year.


Jin NecesarioPosted Sep 4, 2020, 3:11 AM
Nice article, I agree with you most developers schedule are full.