Class: DateValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validators/date_validator.rb

Overview

Checks the date is after|before|not after|not before another date.

validates :next_birthday, date: { after: Time.now, not_after: 1.year.from_now }

Use the :allow_nil key to skip validation in case the attribute value isn’t set.

validates :next_birthday, date: { after: Time.now, allow_nil: true }

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/validators/date_validator.rb', line 15

def validate_each(record, attribute, value)
  return if value.nil? && options[:allow_nil]
  value = value.try(:to_date)
  { after: :>, before: :<, not_after: :<=, not_before: :>= }.each do |key, check|
    if target = options[key].try(:to_date)
      record.errors.add attribute, :"#{ key }_date" unless value.try check, target
    end
  end
end