Date Validation as Text Format in JavaScript

This article is on Date Validation as Text Format in JavaScript. This will validate the Date being in the Text and validate with all the standard features.

There are  lots of validation libraries for Date Validation in JavaScript. By passing an invalid date string, the Date instance would still be created. As an 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. Most of the time, the Date Validation Library doesn’t support String Value for validation. Although some do that, they don’t have the tightly coupled format as a different separator ,like “/” and “-”, can be used in the same date. Moreover, you also have 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 though the code and understand where we want to change, if we want to change the format.
 

Validation Function

  1. function validatedate(dateString){    
  2.     let dateformat = /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01])[\/]\d{4}$/;    
  3.         
  4.     // Match the date format through regular expression    
  5.     if(dateString.match(dateformat)){    
  6.         let operator = dateString.split('/');    
  7.     
  8.         // Extract the string into month, date and year    
  9.         let datepart = [];    
  10.         if (operator.length>1){    
  11.             pdatepart = dateString.split('/');    
  12.         }    
  13.         let month= parseInt(datepart[0]);    
  14.         let day = parseInt(datepart[1]);    
  15.         let year = parseInt(datepart[2]);    
  16.             
  17.         // Create list of days of a month    
  18.         let ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];    
  19.         if (month==1 || month>2){    
  20.             if (day>ListofDays[month-1]){    
  21.                 ///This check is for Confirming that the date is not out of its range    
  22.                 return false;    
  23.             }    
  24.         }else if (month==2){    
  25.             let leapYear = false;    
  26.             if ( (!(year % 4) && year % 100) || !(year % 400)) {    
  27.                 leapYear = true;    
  28.             }    
  29.             if ((leapYear == false) && (day>=29)){    
  30.                 return false;    
  31.             }else    
  32.             if ((leapYear==true) && (day>29)){    
  33.                 console.log('Invalid date format!');    
  34.                 return false;    
  35.             }    
  36.         }    
  37.     }else{    
  38.         console.log("Invalid date format!");    
  39.         return false;    
  40.     }    
  41.     return true;    
  42. }  
In the above "validatedate" function, we can pass a Date String in "MM/DD/YYYY" format. The function implementation is given below:
  1. var a = validatedate("06/16/2019");  
  2. console.log(a);  
This also validates the “M/D/YYYY”, “M/DD/YYYY”, and “MM/D/YYYY” formats.
 
IFfthe date is a valid date in the expected format, the function will return true. Otherwise it will return false. The function will check the date range where ‘04/31/2019’ is a wrong date while it validates the date format. But “MM=04” means, the month is April which ends with 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, wem 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 which specifies the spliced part as 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 “month” and the third part in the “year” variable.
 
In section 2 of the above picture, we have to set the separator/operator as per the required format. For date, there are three operators which are being used: “/”, “-” and “.”. We also change the operator from the “split()” function.
 
And in the section 1, the eegex has to change as per the required format. The date string got verified through the regex in the first step. 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 regex can be easily tested with the help of the following site: https://regexr.com/.
 
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 situation may arise which is an easy problem but hectic to solve. This date string validation is one of them. It’s true that there are a lot of third-party libraries to get help, but when a developer needs to do some modified validation due to a business demand, using those libraries gets hectic. I hope this article will be able to help others.