Class: ActiveRecord::Validations::AgeValidator

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

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/validates_as_age.rb', line 5

def validate_each(record, attribute, value)
  # Default agen range.
  options[:min_age] ||= 18.year
  options[:max_age] ||= 100.year
  
  if value.is_a?(Date) and options[:min_age] <= options[:max_age]
    # Checks if value is inside the given date range.
    return if ((Time.now.to_date - options[:max_age])..(Time.now.to_date - options[:min_age])) === value.to_date
  end
  
  record.errors.add(attribute, 
                    I18n.translate('activerecord.errors.messages.invalid', :default => 'invalid'), 
                    options.merge(:value => value))
end