You are making a mistake a lot of people seem to make (look at the activity in this tag!): you have a goal (in this case, age verification), and have decided that it must be accomplished with regexen. I'm not really sure why people do this—it's not like regexen are a magic panacea that will solve all your problems. The better question to ask is either: (a) "How should I go about performing age validation? I was thinking maybe a regex, but I'm not sure how to write one," or (b) "I'm using technology XYZ, and I need to perform age validation; because XYZ is structured in way PQR, I need to use a regex for this, but I'm not sure how to write one."
So if you're in situation (a), I would say this: why use a regex? I'm not sure how you're getting your input, but there seem to be two cases. If you're getting a single integer value for how old they are, just read it in from wherever you're getting it, convert it into an integer (e.g., via Java's Integer.parseInt(myStringInput)
), and then check that the integer is in range with something like return (18 < age) ? true : false
. If you're getting their birth date (as "years, months, and days" implies), then: read in the years, months, and days; convert them to integers; use them to create an instance of a Date
class; and use its methods for measuring distances between times (again, this depends on your language).
If, on the other hand, you're in situation (b)… ugh. Yes, it would be heinous. If you're in the single-integer situation, it should be doable. If you want to match, say, ages greater than or equal to 18, you should do something like ^(1[8-9]|[2-9]\d|\d{3,})$
: either 18, 19, any two-digit age above the teens, or three-or-more digit ages. If you want to match under-18s, then you want ^(\d|1[0-7])$
. If you're in the birthdate situation, though… again, ugh. I'm not sure how I'd approach it. I hope you aren't. It's definitely doable; I think the right approach is to do something like the above. Match all the years that are before now-18
; if the year is now-18
, do something similar for months; and if the month is the same, do something similar for the days. But I hope you aren't in this situation.
Edit 1: You said you had written some sort of validation structure for the fields which assumed regexen. While I see why that would make you want to use them, it's going to limit what you can validate (and definitely what you can validate sanely). Perhaps it makes more sense to pass a callback function instead, which would let you deal with regexen or things like this.