Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-3158

DateTime#mongoize and Date#mongoize should return nil for invalid strings

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 6.0.0
    • 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
      

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            jfine jfine
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: