How to validate a date? I mean not the format, but the logic. For example: Feb 30th is not a valid date.
var date = new Date("2015-02-29T13:02:49.073Z"); // 2015 Feb 29th does not exist
console.log(date.toISOString());
Returns 2015-03-01T13:02:49.073Z (March 1st).
But I want a information that this date (input) is not valid.
Edit: Tested in Chrome. Firefox returns "invalid date". But not on parsing. Only when the date is used (e.g. toISOString()) an exception is thrown.
try
{
var date = new Date("2015-02-29T13:02:49.073Z");
console.log(date.toISOString());
}
catch(e)
{
console.log("error: " + e.message);
}
Firefox:
invalid date
Chrome:
(nothing, just switched to the next date.)
Summary: It is browser-dependent. So, not recommended to use.
jsfiddle example
The easiest thing I can think of, is to convert the parsed date to ISO string and compare it to the original input:
var input = "2015-02-29T13:02:49.073Z"
var date = new Date(input);
var isValid = (input === date.toISOString());
I use this function to check whether a date is valid or not:
function isValidDate(year, month, day) {
month = month - 1;
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
I wrote small function for you:
function check_date(str){
try{
return str == new Date(str).toISOString()
}catch(e){
return false;
}
}
Try this
console.log(check_date('2015-02-01T13:02:49.073Z'));
console.log(check_date('2015-02-35T13:02:49.073Z'));
console.log(check_date('2015-02-29T13:02:49.073Z'));
https://jsfiddle.net/8o040ctr/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With