codegram / date_validator

A simple, ORM agnostic, Ruby >=2.2 compatible date validator for Rails, based on ActiveModel.
http://thoughts.codegram.com/date-validation-with-rails-3
MIT License
495 stars 82 forks source link

Fail to detect errors when invalid strings are provided #48

Closed pisaruk closed 8 years ago

pisaruk commented 10 years ago

I found two situations where it fails to find errors, and I created two test cases to exhibit the problem:

    it "complains when an invalid date is provided" do
        I18n.backend.reload!
        TestRecord.validates :expiration_date, date: true

        model = TestRecord.new("not a date")
        model.valid?.must_equal false
        model.errors[:expiration_date].must_equal(["is not a date"])
      end
    it "complains when an invalid date is provided and option values evaluates to a negative value" do
        I18n.backend.reload!
        TestRecord.validates :expiration_date, date: { before: 50.years.ago }

        model = TestRecord.new("not a date")
        model.valid?.must_equal false
        model.errors[:expiration_date].must_equal(["is not a date"])
    end

I could not manage to fix them but, for fixing the second case I would start looking at: https://github.com/codegram/date_validator/blob/master/lib/active_model/validations/date_validator.rb#L87.

"not_a_date".to_i

0

and

50.years.ago.to_i

-177126104

Skulli commented 10 years ago

Got the same issues now. Wrong dates as strings like "10.100.2014" are not recognized.

Possible dirty fix could be a validator like this

begin
  if date.is_a?(String)
    date = date.to_date
  end
rescue Exception => e
  errors.add(:date, "invalid date")
end