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
496 stars 82 forks source link

Consider expressions that cannot be type cast to be invalid #37

Closed robworley closed 11 years ago

robworley commented 11 years ago

Useful for ActiveRecord models where string a value is assigned to using Model#attributes=. ActiveRecord will try to type cast the string to a date. When the type cast fails because the string cannot be parsed, it assigns nil to the attribute.

Prior to this change if you specified :allow_nil => true or :allow_blank => true it would incorrectly consider the attribute to be valid. I added some logic to check the value before type cast, taking care to preserve backwards compatibility.

It should resolve issue https://github.com/codegram/date_validator/issues/25. Hope it helps.

robworley commented 11 years ago

The travis build succeeded for the most part, but there's a problem with rbx-2.0. It looks like a travis-specific issue, rather than anything code-related. Maybe someone with rights could try a rebuild?

amnesia7 commented 11 years ago

@robworley, does this allow for virtual attributes as well as actual database-driven attributes?

I have a virtual date attribute in my form which I don't insert directly into a date field in my db. I'm not sure whether or not virtual attributes have _before_type_cast values or not but I don't think so.

Thanks

robworley commented 11 years ago

@amnesia7 sorry for the delayed response.

It's true that virtual ActiveRecord attributes don't have _before_type_cast methods. This change only calls _before_type_cast methods for persistent attributes, so in that sense it's fully backwards compatible.

korny commented 11 years ago

Works great for us, thank you!

robworley commented 11 years ago

@oriolgual, @txus is this PR of interest to you? Anything I need to add or change?

oriolgual commented 11 years ago

Sorry for the late response. Seems OK to me!