To verify if a date is correctly formatted, you can utilize a regular expression like the following:
/^(\d{1,2})([-\.\/])(\d{1,2})\2(\d{4})$/
^
indicates the start of the string, and $
represents the end
\d{1,2}
matches either 1 or 2 digits
\d{4}
corresponds to exactly 4 digits
\2
references the separator captured in the second group (- . /
)
If a match is found, you can extract the day, month, and year values to construct a new date for comparison. Below is a function that accomplishes this:
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)
- The use of
+
converts strings to numbers (e.g., +"01"
becomes 1
)
- Months are indexed from 0 (0 = January, 1 = February, etc.)
- This example assumes the date format as
dd-mm-yyyy
The Date object adjusts erroneous dates automatically. For instance, attempting to create 31-4-2013
results in 1-05-2013
; the above function validates the resulting date against the input parameters.