-
Type: Task
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: None
-
None
Somewhat related to MONGOID-2950. One of the challenges of validating Date and DateTime fields in models is that invalid strings are returning epoch yet empty, nil, or false values are returning nil.
Date.mongoize('invalid') => Thu, 01 Jan 1970 Date.mongoize(nil) => nil Date.mongoize('') => nil Date.mongoize(false) => nil
There are also some inconsistencies in the year when compared to Date#parse.
Date.parse('Jan 31 01').to_s => "2001-01-31" Date.mongoize('Jan 31 01').to_s => "0001-01-31 00:00:00 UTC" Date.parse('Jan 31 78').to_s => "1978-01-31" Date.mongoize('Jan 31 78').to_s => "0078-01-31 00:00:00 UTC"
In our case the field is born_on. If an invalid value of 'bleh' is passed the validations will pass. It would make more sense to set the value to nil instead of epoch for invalid strings since people will have birthdays on 1970-01-01. We are using the current work around but it's clumsy.
validate :born_on_is_valid def born_on_is_valid if born_on_changed? begin # Use parse to raise error since Date#mongoize defaults to epoch for invalid strings Date.parse(born_on_before_type_cast) rescue ArgumentError errors.add(:born_on, "is invalid") end end end
- depends on
-
MONGOID-4269 Use Refinements instead of monkey-patching core classes
- Closed