Class: IsValidMultiparameterDateTimeValidator

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.invalid_format_error_messageObject



25
26
27
28
29
30
31
# File 'lib/is_valid_multiparameter_date_time_validator.rb', line 25

def self.invalid_format_error_message
  date_time = Time.zone.parse('1/29/2000 5:15pm')
  date_string = date_time.strftime(MultiparameterDateTime.date_format)
  time_string = date_time.strftime(MultiparameterDateTime.time_format)

  "Please enter a valid date and time using the following formats: #{date_string}, #{time_string}"
end

Instance Method Details

#date_invalid?(date_value) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
45
# File 'lib/is_valid_multiparameter_date_time_validator.rb', line 41

def date_invalid?(date_value)
  if date_value.present?
    date_invalid = date_value !~ MultiparameterDateTime::VALID_DATE_FORMAT
  end
end

#time_invalid?(time_value) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
# File 'lib/is_valid_multiparameter_date_time_validator.rb', line 33

def time_invalid?(time_value)
  if time_value.present?
    time_invalid_standard = time_value !~ MultiparameterDateTime::VALID_STANDARD_TIME_FORMAT
    time_invalid_military = time_value !~ MultiparameterDateTime::VALID_MILITARY_TIME_FORMAT
    time_invalid_standard && time_invalid_military
  end
end

#validate_each(record, attribute, value) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/is_valid_multiparameter_date_time_validator.rb', line 2

def validate_each(record, attribute, value)
  date_value = record.public_send(:"#{attribute}_date_part")
  time_value = record.public_send(:"#{attribute}_time_part")

  return if date_value.blank? && time_value.blank?

  if date_invalid?(date_value) || time_invalid?(time_value)
    record.errors.add(attribute, self.class.invalid_format_error_message)
  elsif date_value.blank?
    record.errors.add(attribute, 'Please enter a date.')
  elsif time_value.blank?
    record.errors.add(attribute, 'Please enter a time.')
  else
    attribute_value = record.public_send(:"#{attribute}_time_part")
    begin
      Time.zone.parse("#{date_value} #{time_value}")
      Time.zone.parse(attribute_value)
    rescue ArgumentError
      record.errors.add(attribute, self.class.invalid_format_error_message)
    end
  end
end