You can check if a date is syntactically correct using a regex such as this one:
/^(\d{1,2})([-\.\/])(\d{1,2})\2(\d{4})$/
^
and $
match beginning and end of string respectively
\d{1,2}
matches 1 or 2 digits
\d{4}
matches exactly 4 digits
\2
matches the string captured in second capturing group (- . /
)
If matched, you can use the matched date, month and year to build a new date and compare the resulting date, month, year with the matched values. Here is a function which does just that:
function checkDate(dateText) {
var match = dateText.match(/^(\d{1,2})([-\.\/])(\d{1,2})\2(\d{4})$/);
// "31.04.2012" -> ["31.04.2012", "31", ".", "04", "2012"]
if (match === null) {
return false;
}
var date = new Date(+match[4], +match[3] - 1, +match[1]);
return date.getFullYear() == +match[4] &&
date.getMonth() == +match[3] - 1 &&
date.getDate() == +match[1];
}
checkDate("30.04.2013"); // true
checkDate("31-04-2013"); // false (April has 30 days)
+
is used to convert string to number (+"01"
becomes 1
)
- Months are 0 based (0 = January, 1 = February, ...)
- The above example assumes that the date is in
dd-mm-yyyy
format
The Date object attempts to correct invalid dates. Attempting to create a date such as 31-4-2013
yields 1-05-2013
, the above function compares the resulting date with input parameters to check the validity.