I want to validate dates by Javascript
and found this nice answer:
https://stackoverflow.com/a/1353711/3391783
but when i try to use it to validate dates, it seems like Javascript
is auto-correcting my date by taking the closest valid date. so this will return true
even though 2014-11-31
is not a valid date (Javascript
months start at 0
, so 10
equals November):
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
var test_date = new Date(2014, 10, 31);
console.log( test_date );
console.log( isValidDate(test_date) );
seems like creating the Date
is automatically switching it to 2014-12-01
which is a correct date.
but I would like to be able to validate user input without changing it.
So how can i create an invalid new Date()
in Javascript
?
Or is there a much simpler way to do this?