Skip to content

Differentiating between blank and not_a_date #62

Open

Description

@CeeBeeUK

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:

  • nil to validates :dob, date: true would return en.errors.messages.blank
  • 'bob' to validates :dob, date: true would return en.errors.messages.not_a_date

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

Activity

  1. dgmstuart commented on Mar 16, 2016

    @dgmstuart

    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.

  2. mlt commented on Sep 25, 2017

    @mlt

    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"]

  3. dgmstuart commented on Sep 25, 2017

    @dgmstuart

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

    def validate_each(record, attr_name, value)
    before_type_cast = :"#{attr_name}_before_type_cast"
    value_before_type_cast = if record.respond_to?(before_type_cast)
    record.send(before_type_cast)
    else
    nil
    end
    if value_before_type_cast.present? && value.nil?
    record.errors.add(attr_name, :not_a_date, options)
    return
    end
    return if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
    unless value
    record.errors.add(attr_name, :not_a_date, options)
    return
    end

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

  4. mlt commented on Sep 26, 2017

    @mlt

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions