From: Ne Scripter Date: 2009-09-07T20:43:19+09:00 Subject: Re: Date & time validation Thanks all for the responses. I am still hitting a bit of a block with this, initially I want to check if a date matches this criteria, then if not do some of the processes that have been suggested. I need to say if date = yyyy/mm/dd puts date else validate date end How would I do this? Sorry for so many questions, I am struggling to get my head around the date libraries Many thanks Robert Klemme wrote: > 2009/9/1 Brian Candler : >> Max Williams wrote: >>> date = (string =~ /^\d{4}\/\d{2}\/\d{2}$/) && >> >> Beware: use >> >> date = (string =~ /\A\d{4}\/\d{2}\/\d{2}\z/) ... >> >> or else malicious inputs may be able to bypass your validation. (They >> might not be able to bypass Date.strptime in this particular instance, >> but still you ought to validate correctly) > > Then you can do: > > 16:48:53 ~$ irb19 -r date > Ruby version 1.9.1 > irb(main):001:0> %w{2009/10/11 2009/10/44}.each do |s| > irb(main):002:1* p s > irb(main):003:1> date = %r{\A(\d{4})/(\d{2})/(\d{2})\z} =~ s && > Date.new($1.to_i, $2.to_i, $3.to_i) > irb(main):004:1> end > "2009/10/11" > "2009/10/44" > ArgumentError: invalid date > from /opt/lib/ruby19/1.9.1/date.rb:809:in `civil' > from (irb):6:in `block in irb_binding' > from (irb):4:in `each' > from (irb):4 > from /opt/bin/irb19:12:in `
' > irb(main):005:0> > > Cheers > > robert -- Posted via http://www.ruby-forum.com/.