Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails date check if parsable

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

like image 327
Shalafister's Avatar asked Dec 06 '22 18:12

Shalafister's


2 Answers

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
like image 169
Mihai Dinculescu Avatar answered Dec 21 '22 03:12

Mihai Dinculescu


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])
like image 22
Малъ Скрылевъ Avatar answered Dec 21 '22 02:12

Малъ Скрылевъ