I’ve recently been looking for a regular expression to do some client side date checking, and I haven’t been able to find one that can satisfy the following criteria:
- Has a range from 1800 – Now
- Performs proper date checking with leap years
- MM/DD/YYYY Form
- Invalid Date Checking
(These constraints were outside of my scope and are a requirement as per the client, despite my efforts to convince them this wasn’t the best route)
Current code:
$('input').keyup(function()
{
var regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
$(this).toggleClass('invalid',!regex.test($(this).val()));
});
Update:
I should note that this is primarily to see if a regular expression like this would be possible (as the use of a Regex is not my choice in this matter). I am aware of the other (and better) options for validating a date, however as previously mentioned – this is to see if it was possible through a regular expression.
As is mentioned elsewhere, regular expressions almost certanily not what you want. But, having said that, if you really want a regular expression, here is how it is built:
31 day months
30 day months
February 1-28 always valid
February 29 also valid on leap years
which means it would be this if you put it all together:
This version is a little shorter, but a little harder to understand.
These scripts are long and unmaintainable. It should be clear that this isn’t a good idea, but it is possible.
Caveats:
[\/.]as seperators (8 places)