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
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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With