Update 5/31/2008: Use ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS
I have invested some time to get Rails date validation to work (whoo hoo!).
Without further ado, here are the step by step instructions:
1. Download Rails Date Kit from my site. Note that I got the original kit from http://www.methods.co.nz/rails_date_kit/rails_date_kit.html.
Extract the files in rails_date_kit_1.2.0.tar.gz to <your application>/vendor/plugins/rails_date_kit.
2. Get the Validates Date Time plugin by running the following command in your application directory:
script/plugin install http://svn.viney.net.nz/things/rails/plugins/validates_date_time
You should have a new directory in your <your application>/vendor/plugins/validates_date_time
3. Put the necessary files in the right places.
Copy vendor/plugins/rails_date_kit/calendar.js to public/javascripts
Copy vendor/plugins/rails_date_kit/calendar.css to public/stylesheets
Copy vendor/plugins/rails_date_kit/calendar_prev.png to public/images
Copy vendor/plugins/rails_date_kit/calendar_next.png to public/images
Copy vendor/plugins/rails_date_kit/date_helper.rb to app/helpers
4. Include the css and javascript files for the calendar in your page header (e.g. view/layout/tasks.html.erb):
<%= stylesheet_link_tag ‘calendar.css’ %>
<%= javascript_include_tag ‘calendar’ %>
My application uses application.rhtml, thus I just added the lines there.
5. Create a new file called date_formats.rb in config/initializers. All you need to add is:
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default_date => ‘%m/%d/%Y’)
Note the capital Y in ‘%m/%d/%Y’. Obviously, you can add more date formats as needed.
Update: Adjust the date format accordingly to your locale. For example, use ‘%d/%m/%Y’ for displaying date/month/year.
6. Use the following code to add the date field in your input form (e.g. view/tasks/new.html.erb):
<%= date_field :task, :due_date, :format => ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default_date], :value => @task.due_date %>
You can also wrap the whole ‘ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default_date]‘ into a function in app/helpers/application_helper.rb.
6. Tell your model to use en-us date format by adding the following line:
ValidatesDateTime.us_date_format = true #use mm/dd/yyyy format
Update: Set ValidatesDateTime.us_date_format to ‘false’ if your date format is not month/date/year.
7. Validate away!
Here’s an example of my model validation:
Class Task < ActiveRecord::Base
.
.
validates_date :due_date, :allow_nil => true
.
.
End
Enjoy!
Post any questions in the comment.