How to get strptime to raise ArgumentError with garbage trailing characters

Posted by Matt Briggs on Stack Overflow See other posts from Stack Overflow or by Matt Briggs
Published on 2010-06-03T17:10:23Z Indexed on 2010/06/03 18:14 UTC
Read the original article Hit count: 328

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about validation