Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match a valid day in a date

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.

like image 744
Zerobu Avatar asked May 20 '11 19:05

Zerobu


People also ask

How does regular expression validate time in 24 hour format?

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] ›.

Which of the following regular expression passes the calendar date?

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.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.


1 Answers

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])
like image 187
bluepnume Avatar answered Oct 11 '22 08:10

bluepnume