I want to validate a date in my model in Ruby on Rails, however, the day, month and year values are already converted into an incorrect date by the time they reach my model.
For example, if I enter February 31st 2009 in my view, when I use Model.new(params[:model])
in my controller, it converts it to "March 3rd 2009", which my model then sees as a valid date, which it is, but it is incorrect.
I would like to be able to do this validation in my model. Is there any way that I can, or am I going about this completely wrong?
I found this "Date validation" that discusses the problem but it never was resolved.
Here's a non-chronic answer..
Have you tried the
validates_date_time
plug-in?I'm guessing you're using the
date_select
helper to generate the tags for the date. Another way you could do it is to use select form helper for the day, month, year fields. Like this (example I used is the created_at date field):And in the model, you validate the date:
If you're looking for a plugin solution, I'd checkout the validates_timeliness plugin. It works like this (from the github page):
The list of validation methods available are as follows:
Active Record gives you
_before_type_cast
attributes which contain the raw attribute data before typecasting. This can be useful for returning error messages with pre-typecast values or just doing validations that aren't possible after typecast.I would shy away from Daniel Von Fange's suggestion of overriding the accessor, because doing validation in an accessor changes the accessor contract slightly. Active Record has a feature explicitly for this situation. Use it.
Using the chronic gem:
Since you need to handle the date string before it is converted to a date in your model, I'd override the accessor for that field
Let's say your date field is
published_date
. Add this to your model object: