Skip to content

Instantly share code, notes, and snippets.

@varnie
Created September 7, 2011 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varnie/1199866 to your computer and use it in GitHub Desktop.
Save varnie/1199866 to your computer and use it in GitHub Desktop.
A regexp for date validation
=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