Easy JavaScript date validation with two lines of code

  • 2021-07-09 06:41:02
  • OfStack

We usually verify the date in JavaScript. The basic idea is to judge whether the year, month and day are valid first, and then judge whether there is a day in the current month, for example, there is no 31st in January, no 29th and 30th in February in ordinary years, and no 30th in February in leap years.

Accidentally found a skill to judge all the above situations. Excluding the assignment code, the actual code is only two lines.

In fact, this technique is also very simple, by instantiating Date object to generate a legal date, and then compare whether the year, month and day are equal to verify whether the date is legal.


var originalYear = 2016;
var originalMonth = 12;
var originalDay = 32;
var date = new Date(originalYear, originalMonth - 1, originalDay);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
console.log(year + '-' + month + '-' + day); // 2017-1-1 

Because there is no 32 days in December, the export date is January 1 of the second year, and the years, months and days are not equal, so December 32, 2016 is not a legal date.

Specific implementation code:


 var validateDate = function (originalYear, originalMonth, originalDay) {
 var date = new Date(originalYear, originalMonth - 1, originalDay);
 var year = date.getFullYear();
 var month = date.getMonth() + 1;
 var day = date.getDate();
 return year == originalYear && month == originalMonth && day == originalDay;
} 

Test:


console.log(validateDate()); // false
console.log(validateDate(-1, -1, -1)); // false
console.log(validateDate('', '', '')); // false
console.log(validateDate([], [], [])); // false
console.log(validateDate({}, {}, {})); // false

//  Average year 2 Month. 
console.log(validateDate(2015, 2, 29)); // false
//  Leap year 2 Month. 
console.log(validateDate(2016, 2, 29)); // true
console.log(validateDate(2016, 6, 30)); // true
console.log(validateDate(2016, 6, 31)); // false
console.log(validateDate('2016', '01', '01')); // true


Related articles: