We have to handle user specified date formats in our application. We decided to go with Date.strptime for parsing and validation, which works great, except for how it just ignores any garbage data entered. Here is an irb session demonstrating the issue
ree-1.8.7-2010.01 > require 'date'
=> true
ree-1.8.7-2010.01 > d = Date.strptime '2001-01-01failfailfail', '%Y-%m-%d'
=> #<Date: 4903821/2,0,2299161>
ree-1.8.7-2010.01 > d.to_s
=> "2001-01-01"
what we would like, is behavior more like this
ree-1.8.7-2010.01 > d = Date.strptime '2001failfailfail-01-01', '%Y-%m-%d'
ArgumentError: invalid date
Any suggestions would be appreciated
One possibility is to pass the resulting date through
strftimeusing the same format and compare to the original string.i.e.
valid = Date.strptime(date_string, format).strftime(format) == date_stringOne limitation of this is that it wouldn’t handle leading 0s in parts of the date e.g. if you wanted to accept 2010-6-1 but
strftimereturned 2010-06-01 you wouldn’t have a match.Also, I’m not sure if this is what you meant or not, but your second example
Date.strptime '2001failfailfail-01-01', '%Y-%m-%d'does raise anArgumentError. It seems like only trailing junk is ignored.