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

Differentiating between `blank` and `not_a_date` #62

Open CeeBeeUK opened 9 years ago

CeeBeeUK commented 9 years ago

Hello,

I'm trying to set up date validation on a field that requires a valid date be input.

validates :dob, date: true, presence: true renders both the blank and not_a_date messages.

I am working on a fork that would change the functionality so that passing:

Is this something that would be welcomed as a pull request or should I keep it separate?

dgmstuart commented 8 years ago

Yup - I've been bitten by that one. The solution is to use

date: { allow_blank: true }

So the date validation won't get run if date is not present.

mlt commented 6 years ago

I have something like

  validates :effective_to, date: { allow_blank: true, after: :effective_from }

It complains if effective_to is blank :( ["Effective to is not a date"]

dgmstuart commented 6 years ago

@mlt Here's a section of code involved, which suggests that your code above should work:

https://github.com/codegram/date_validator/blob/0a1f7aecac9c8afe3967dd622767505df607b7e4/lib/active_model/validations/date_validator.rb#L52-L71

A blank string can be many things: nil, empty string, string containing only whitespace, false - which is it in your scenario?

mlt commented 6 years ago

My bad! I was messing around with parameter coercion substitution that I want to treat blank as infinite. This fragment indeed does work! However, there is another problem. It doesn't respect DateTime::Infinity that was coming from my strong params filter. I forgot I added

      p[:effective_to] = DateTime::Infinity if p.fetch(:effective_to, '').blank?

Note, that

validates :effective_to, date: { after: :effective_from }, unless: Proc.new{ |p| p.effective_to.blank? }

worked fine with blank (actually infinite) parameter. It seems to me they should be equivalent.