You can do it with Regular Expressions, but it makes no practical sense.
Let me explain you a very general idea related to validation, which is applicable to many platforms, technologies and languages.
First of all, think why would you need validation? You only need to validate your string if you plan to get a
Date
value from that string. So, you don't need validation per se, you only need to know if the string is "good enough" to be uses for creation of the
Date
object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date[
^].
But when you get a
Date
object from string, the result can be valid or not. Why doing two separate steps if you can do validation and construction in one step? This "validation through construction" is not error-prone, in contrast to your Regular Expression attempts, because the constructor "knows better" what is valid and what not.
The specific feature of JavaScript
Date
constructors is: they don't throw exception, don't return "error code", nothing. It's very typical for JavaScript technology. So, you simply need to obtain
Date
object and validate it, not string. What would be the validation method? I would suggest this one:
function isValid(date) {
var value = date.valueOf();
if (value === 0) return true;
else return !!value;
}
var a = new Date("12/11/2013 11:20:13");
if (isValid(a)) { }
var b = new Date("??/11/2013 11:20:13");
if (isValid(b)) { }
I hope it's clear. In case of the valid time value, the function
Date.prototype.valueOf()
returns an integer value, the number of milliseconds, which is the time span from the certain point of time in 1970:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf[
^].
In case of invalid date, the browsers I tried return NaN, but I did not check it up with the standard. Even if I assume that different browsers can do something else, they still should return a number for a valid
Date
object. '!!' converts result to Boolean, which will be true in all cases when the time is valid. Zero is a special case: it would be converted to False, but is certainly valid. '===' (not '==') is important: it compares with 0 of numeric type, not mixing it, with, say, "0".
—SA