Class: Document::DateRangeValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/models/document/date_range_validator.rb

Overview

DateRangeValidator

Instance Method Summary collapse

Instance Method Details

#valid_yyyy(date) ⇒ Object



58
59
60
61
62
63
64
# File 'app/models/document/date_range_validator.rb', line 58

def valid_yyyy(date)
  if date[/\D/]
    false unless date == "*"
  else
    true
  end
end

#validate(record) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/document/date_range_validator.rb', line 10

def validate(record)
  valid_date_ranges = true
  record.send(GeoblacklightAdmin::Schema.instance.solr_fields[:date_range]).each do |date_range|
    # Empty is fine
    if date_range.blank?
      valid_date_ranges = true
      return valid_date_ranges
    end

    # Must split into two via '-'
    if date_range.split("-").size != 2
      record.errors.add(GeoblacklightAdmin::Schema.instance.solr_fields[:date_range],
        "invalid date range present - missing YYYY-YYYY value")
      valid_date_ranges = false
      return valid_date_ranges
    end

    start_date, end_date = date_range.split("-")

    unless valid_yyyy(start_date)
      record.errors.add(GeoblacklightAdmin::Schema.instance.solr_fields[:date_range],
        "invalid start date - bad YYYY-YYYY value, only integers or the wildcard '*' allowed")
      valid_date_ranges = false
    end

    unless valid_yyyy(end_date)
      record.errors.add(GeoblacklightAdmin::Schema.instance.solr_fields[:date_range],
        "invalid end date - bad YYYY-YYYY value, only integers or the wildcard '*' allowed")
      valid_date_ranges = false
    end

    # Allow only 1 wildcard
    if start_date == "*" && end_date == "*"
      record.errors.add(GeoblacklightAdmin::Schema.instance.solr_fields[:date_range],
        "invalid only one wildcard can be used")
      valid_date_ranges = false
    end

    # Avoid 1996-1946
    next unless start_date[/\d+/] && end_date[/\d+/] && start_date.to_i > end_date.to_i

    record.errors.add(GeoblacklightAdmin::Schema.instance.solr_fields[:date_range],
      "invalid start date must be less than the end date")
    valid_date_ranges = false
  end
  valid_date_ranges
end