4

I have a datetime picker which sends the checkin & checkout dates with search box. Then the url looks like;

http://localhost:3000/locations/listings?utf8=%E2%9C%93&search=london&start_date=12%2F04%2F16&end_date=20%2F04%2F16

and I take the params hash and parse the string,

start_date = Date.parse(params[:start_date])
end_date = Date.parse(params[:end_date])

first of all, I have to check if (start_date.present? && end_date.present?) and that works fine.

But if the user manually types something else rather than the date to url such as;

http://localhost:3000/locations/listings?utf8=%E2%9C%93&search=london&start_date=londoneye6&end_date=20%2F04%2F16 

Then of course I get an error;

invalid date

How should I control if the string is parsable on controller action. I should be also checking london-eye, london/eye strings, which include - /

Thank you

Shalafister's
  • 761
  • 1
  • 7
  • 34

2 Answers2

11

You have to try parsing the string and rescue ArgumentError

begin
   myDate = Date.parse("31-01-2016")
rescue ArgumentError
   # handle invalid date
end

one line (please note that this rescues all errors)

myDate = Date.parse("31-01-2016") rescue nil
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
5

You can validate time with Date.parse, and just trap ArgumentError exception on parse returning nil out:

controller:

def param_date date
   Date.parse(date)
rescue ArgumentError
   nil
end

start_date = param_date(params[:start_date])
end_date = param_date(params[:end_date])
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69