Class: StrictDateValidator

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

Overview

This validator will fail if the date provided is an 'InvalidDate' - or whichever invalid date class is passed into its config. This allows the form object to store an 'InvalidDate' which contains the original values passed by the user which keeps it happy as it is still a 'Date' - just an invalid one.

The custom active model type 'strict_date' is responsible for returning these special types

Examples:

Simple Usage


validates :date_of_birth, date: true

With custom invalid date class


validates :date_of_birth, date: { invalid_date_class: CustomInvalidDate }

Instance Method Summary collapse

Constructor Details

#initialize(invalid_date_class: InvalidDate, **args) ⇒ StrictDateValidator

Returns a new instance of StrictDateValidator


17
18
19
20
# File 'app/validators/strict_date_validator.rb', line 17

def initialize(invalid_date_class: InvalidDate, **args)
  self.invalid_date_class = invalid_date_class
  super(args)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object


22
23
24
25
# File 'app/validators/strict_date_validator.rb', line 22

def validate_each(record, attribute, value)
  return if value.nil? || value.blank?
  record.errors.add(attribute, :invalid_date) if value.is_a?(invalid_date_class)
end