Adding additional date format checking to the Rails Date Kit
May 4th, 2007 by Robert Dempsey - Tags: Ruby on Rails
In a recent project, we used the Rails Date Kit to quickly add a cool drop down calendar for our _form.rhtml pages as well as our search forms. While most users will use the calendar for date entry, there will be those who manually enter a date when they tab into the field. The Rails Date Kit has a date validation that works great for creating/editing/updating records, however it wasn’t working for our search form. In addition, with MySQL, when we would enter in a search date in the ‘%m/%d/%Y’ format, it didn’t like it and wouldn’t return any results. To ensure that our users entered dates into the search in a “supported” format, and that our searches returned results, we did the following:
In environment.rb, we added the following:
ActiveRecord::Validations::DateTime.us_date_format = true
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
:default => ‘%m/%d/%Y’,
:search_date => ‘%Y-%m-%d’
)
After that, we decided which date formats we wanted to support and added a little function to our controller:
def parse_the_date(date)
# An array to hold our formats: US, four digit year, European
try_formats = ['%m/%d/%y', '%m/%d/%Y', '%d/%m/%y']
parsed = nil
try_formats.each do |format|
begin
parsed = Date.strptime(date, format)
break
rescue ArgumentError
end
end
return parsed
end
Finally, in our search function, we grab the date and add a dash of error handling:
date_from = params[:controller][:date_from]
unless date_from.nil?
if date_from.is_a?(Date)
date_from = parse_the_date(date_from).to_s(:search_date)
else
flash[:error] = “The date from field needs to be in the format mm/dd/yyyy. 1/1/2007 and 1/1/07 would be correct.”
end
end
Let me explain that little snippet there. We first check to see if we need handle the parameter. If it doesn’t exist, keep moving. If it does exist, down the rabbit hole we go. We ensure that the user entered in a properly formatted date. If not, we flash an error message to tell them the correct format. If everything is in line, we enter our function, checking our supported formats, ultimately returning the date in our format. Finally, we use the date formatting from environment.rb to put the date into a format that MySQL likes.
I would like to thank the Ruby Cookbook for giving me a leg up on this issue. If anyone knows of a better way to do it, please post it here. Good luck and happy coding!
You can leave a response, or trackback from your own site.