adzap / validates_timeliness

Date and time validation plugin for ActiveModel and Rails. Supports multiple ORMs and allows custom date/time formats.
MIT License
1.59k stars 227 forks source link

Using option :format method timeliness_type_cast_code ignores given :format #125

Closed phlegx closed 9 years ago

phlegx commented 9 years ago

Using the following validation:

validates :published_at, presence: true, timeliness: { type: :datetime, format: 'dd.mm.yyyy, hh:nn' }

The validation returns an error that the attribute must be set. This is caused by the method timeliness_type_cast_code(attr_name, var_name) in file https://github.com/johncarney/validates_timeliness/blob/master/lib/validates_timeliness/attribute_methods.rb#L65

The Timeliness::Parser.parse() call ignores the :format option set in the validation.

"#{var_name} = Timeliness::Parser.parse(#{var_name}, :#{type}, :zone => #{timezone.inspect})"

Any idea how t add :format option dynamically to Timeliness::Parser.parse()?!

phlegx commented 9 years ago

I have solved the problem by adding the following line in the config:

ValidatesTimeliness.setup do |config|
  config.use_plugin_parser = true
  config.parser.add_formats(:datetime, 'dd.mm.yyyy, hh:nn')
end
adzap commented 9 years ago

Yep you got it. Type casting and validation are not the same thing. Typecasting should any valid value. The validation should block the valid acceptance of a value for more specific reasons e.g. in comparison to another value or, in your case a specific format.