Date Validation as Text Format in JavaScript

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.

Change the Function for Other Formats

To use the function for other date formats, we need to change the following 3 positions.

  1. The Regex
  2. The operator/Separator
  3. Date string Part Sequence

Let's start with number 3, the Date String part sequence, specifying the spliced part per the required date format. If we want to set the format as "DD/MM/YYYY", then we need to set the first part of the Date string in the "day" variable, the second part in the "month", and the third part in the "year" variable.

In section 2 of the above picture, we must set the separator/operator as per the required format. We also change the operator from the "split()" function. For date, there are three operators which are being used: "/", "-" and ".".

The date string got verified through the regex in the first step. And in section 1, the regex has to change as per the required format. A regex table is given below for some date formats.

Sample Regex for Date Format
 

Date Format Regex
MM/DD/YYYY  
M/DD/YYYY /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01])
MM/D/YYYY [\/]\d{4}$/
M/D/YYYY  
DD/MM/YYYY  
D/MM/YYYY  /^(0?[1-9]|[1-2][0-9]|3[01])[\/](0?[1-9]|1[0-2])
DD/M/YYYY  [\/]\d{4}$/
D/M/YYYY  

These regexes can be easily tested with the help of the following site: https://regexr.com/.

Summary

This is a quite simple function to use and change. My motive to share this with the community is because sometimes when we work with JavaScript, some situations may arise, which is an easy problems but hectic to solve.

There are many third-party libraries to get help, but when a developer needs to do some modified validation due to business demand, using those libraries gets hectic. I hope this article will be able to help others. This date string validation is one of them.