javascript date validation not validation February 31
Due to what I said in the comments...
Another way you could check if a date is valid is by checking whether or not the stuff you passed into the new Date
function is the same as what comes out of it, like this:
// Remember that the month is 0-based so February is actually 1...
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
then you could do this:
if (isValidDate(2013,1,31))
and it would return true
if valid and false
if invalid.
After wrecking my head with the obscurity of Date
.getMonth()
(and also weekday by .getDay()
) being 0-index
(despite year, day and all the others not being like so... oh god...) I've re-wrote Jeff's answer to make it more readable and more friendly-usable to whom consume the method from outside.
ES6 code
You can call passing month as 1-indexed
as you'd normally expect.
I've parsed inputs using Number constructor so I can use strict equality to more confidently compare values.
I'm using the UTC
version methods to avoid having to deal with the local timezone.
Also, I broke steps down into some variables for the sake of readability.
/**
*
* @param { number | string } day
* @param { number | string } month
* @param { number| string } year
* @returns { boolean }
*/
function validateDateString(day, month, year) {
day = Number(day);
month = Number(month) - 1; //bloody 0-indexed month
year = Number(year);
let d = new Date(year, month, day);
let yearMatches = d.getUTCFullYear() === year;
let monthMatches = d.getUTCMonth() === month;
let dayMatches = d.getUTCDate() === day;
return yearMatches && monthMatches && dayMatches;
}