Anyone have a good regex for Age verification?
I have a date field where I am validating that what the user enters is a date.
basically I wanted to figure out if that date is valid, and then further refine the date to be within x number of years
Perhaps this may be too complicated to tack onto whatever I have too far, but I figured it wouldn’t be.
^([1][012]|[0]?[1-9])[/-]([3][01]|[12]\d|[0]?[1-9])[/-](\d{4}|\d{2})$
I’m a big fan of regexes, and of course it’s possible to check a date against a “legal range” using regexes.
BUT:
Matching a valid date (without fancy stuff like checking for leap years) is fairly trivial but tiresome by regex – a tool for constructing regexes like RegexMagic will do this for you quickly:
is what RegexMagic generates for MM/DD/YYYY date validation without imposing limits on date ranges (i.e. 02/31/2020 won’t match, 01/31/4500 will).
This is already ugly and probably quite hard to figure out if you’re the one inheriting this code.
The second problem, namely validating against a predefined date range is even uglier. It can be done, but
you’d need to change your regex
every single day – after all, every
day, someone turns 18, don’t they?
and
the regex would get even more unwieldy. To allow anything from 06/10/1992 until
06/10/2010, you get
this monster of a regex.
(linebreaks included for “clarity”).
Tomorrow, you’ll need
Notice the subtle difference?
In short, as all the others have pointed out: This is not something you want to use a regular expression for. Even if you can.