I’m trying to validate two date attributes in order that they be consecutive.
The gem validates_timeliness is excellent to validate incorrect dates such as february the 31th.
However I’m trying to make use of :before and :after parameters, but it doesn’t work. It accept a start date of 31 december 2012 while the end date is set to 1st january 2012.
My model :
class Meeting < ActiveRecord::Base
attr_accessible :date_start, :date_end
validates :date_start, :date_end, :presence => true
# Ressource : https://github.com/adzap/validates_timeliness
validates_date :date_start, :before => :date_end
validates_date :date_end, :after => :date_start
end
Does validates_timeliness allow to do what I want or isn’t it built for this ?
I would prefer to avoid to use two gems just for handling dates in my app. I mean using validates_timeliness gem with date_validator gem as well.
===== UPDATE =====
There is something that is not working properly with validates_timeless though I can’t find a reason why.
It accepts date_start to be after today even if I set the following validation in my model :
validates_date :date_start, :before => lambda { Date.current }
my /config/initializers/validates_timeliness.rb (for info) :
ValidatesTimeliness.setup do |config|
# Extend ORM/ODMs for full support (:active_record, :mongoid).
config.extend_orms = [ :active_record ]
# Re-display invalid values in date/time selects
config.enable_date_time_select_extension!
# Handle multiparameter date/time values strictly
config.enable_multiparameter_extension!
# Shorthand date and time symbols for restrictions
config.restriction_shorthand_symbols.update(
:now => lambda { Time.current },
:today => lambda { Date.current }
)
# Use the plugin date/time parser which is stricter and extendable
config.use_plugin_parser = false
end
Note that if I try to set the date 31th February, I got an error message telling the date is incorrect. I also restart my server each time after a config change.
===== UPDATE 2 =====
I even tried this invalid hash_key, and Rails doesn’t complain :
validates_date :date_start, :blablabla => lambda { Date.current }
So what’s going on ? what am I doing wrong ?
===== UPDATE 3 =====
It seems to be a bug.
These two options do work :
validates_date :date_start, :on_or_before => lambda { Date.current }
validates_date :date_start, :on_or_after => lambda { Date.current }
These two options do NOT work :
validates_date :date_start, :before => lambda { Date.current }
validates_date :date_start, :after => lambda { Date.current }
I’m using Rails 3.2.9 and Ruby 1.9.3p194.
Could anybody confirm he has the same issue ?
I haven’t used this gem, but it seems they support lambda’s for the values. Try the following which (should) pass your Meeting instance into the lambda and return the result to the validation method. It has to be done in a lambda since it’s instance specific.