I need help coming up with a regex to make sure the user enters a valid date
The string will be in the format of mm/dd/yyyy
Here is what I have come up with so far.
/\[1-9]|0[1-9]|1[0-2]\/\d{1,2}\/19|20\d\d/
I have validated the regex where the user cannot enter a day higher than 12 and the years have to start with either "19" or "20". What I am having trouble is figuring out some logic for validating the day. The day should not go over 31.
In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.
A regular expression for dates (YYYY-MM-DD) should check for 4 digits at the front of the expression, followed by a hyphen, then a two-digit month between 01 and 12, followed by another hyphen, and finally a two-digit day between 01 and 31.
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
Regex for 0-31:
(0[1-9]|[12]\d|3[01])
Or if you don't want days with a preceding zero (e.g. 05):
([1-9]|[12]\d|3[01])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With