Class: DateFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/date_format_validator.rb

Overview

Validate fields to be parseable dates

A blank date is considered valid (use presence validator to check for that)

Examples

validates :date, date_format: true                 # optional
validates :date, date_format: true, presence: true # required

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr_name, value) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'app/validators/date_format_validator.rb', line 9

def validate_each(record, attr_name, value)
  return if value.blank?
  return if value.class == Date # if value is already Date it must be valid

  begin
    Date.parse(value)
  rescue
    record.errors.add(attr_name, :date_format, options)
  end
end