Although @Adirkuhn has already provided an acceptable solution to AP. After seeing this I went looking for something more powerful, that could at least validate months with 30 and 31 days, because I knew that this was possible, despite knowing that it was laborious.
Then I found that answer in Soen, which was beyond my expectations, as it is valid until dates for leap years (in this case the 29th of February).
Then after some adaptations to the Portuguese language (I removed the option of 01/Feb/2015
, only accepting months in numbers: 01/02/2015
), share this powerful regular expression to validate dates:
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
The flow chart of the expression for better understanding:
Online example in the tool used to debug and generate the Regular Expression flowchart (Debuggex)
The problem is that regular expressions do not understand that values can only go from X to Y, as in the case of days, which vary with the month (makes the problem even worse!) and with the year (for February). What can be done is validate the date after capturing it.
– mutlei
In fact, you are demanding of regular expressions much more than this tool is capable of... How about using regex only to eliminate "obvious" cases (i.e. accept false positives, just don’t let it have false negatives) then doing a more rigorous validation, using the calendar functions of your platform?
– mgibsonbr
If possible, follow is my late solution, validating months of 30 and 31 days, including 29 February for leap years.
– Fernando Leal