Created
September 7, 2011 05:49
-
-
Save varnie/1199866 to your computer and use it in GitHub Desktop.
A regexp for date validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin rdoc | |
Checks that the supplied date has the correct date format '#YYYY:MM:DD' with the separators both be either - or : or /. | |
A year cannot start from the zero, while a month and a day can. | |
Doesn't check that the supplied day is within the specified month's day range. It may be further improved. | |
=end | |
def checkDate(aDate) | |
%r{ | |
(?<year> | |
(^ #no input before the start | |
[1-9]\d{3} #a year cannot start from the zero | |
) | |
) | |
(?<sep>-|:|/) #a separator can be either - or : or / | |
(?<month> | |
(0[1-9]) #a month can start from the zero | |
| | |
(1[0-2]) #or it could be just 10, 11 or 12 of course | |
) | |
\k<sep> #the 2nd separator must be the same as the 1st met | |
(?<day> | |
(0[1-9]) #a day can start from the zero | |
|(1[0-9]) #or should fall into the range [1..31] | |
|(2[0-9]) | |
|30 | |
|31 | |
)$ #marks there should be the end of the input | |
}x =~ aDate | |
end | |
date = "1234:12:31" | |
print "date is #{checkDate(date) ? "" : "not "}correct" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment