Skip to content

Commit

Permalink
Add date validation on application progress
Browse files Browse the repository at this point in the history
  • Loading branch information
fumimowdan committed Oct 16, 2023
1 parent 3493901 commit 2d599ae
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 13 deletions.
41 changes: 28 additions & 13 deletions app/validators/application_progress_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,19 @@ def valid?
private

def process_date_params
DATE_PARAMS.each do |date_param|
day, month, year = extract_date_components(date_param)
DATE_PARAMS.each { |date_param| process_date_param(date_param) }
end

def process_date_param(date_param)
day, month, year = extract_date_components(date_param)
return if year.blank? && month.blank? && day.blank?

field_date = parse_date(year, month, day)

if year.blank? && month.blank? && day.blank?
@progress[date_param] = nil
elsif valid_date?(year, month, day)
@progress[date_param] = Date.new(year.to_i, month.to_i, day.to_i)
else
@progress.errors.add(date_param, "is not a valid date")
@progress[date_param] = InvalidDate.new(day:, month:, year:)
end
end
return invalid_date(date_param, day, month, year) unless field_date
return invalid_date_range(date_param, field_date) if date_out_range?(field_date)

@progress[date_param] = field_date
end

def extract_date_components(date_param)
Expand All @@ -54,9 +55,23 @@ def process_non_date_params
remaining_params.each { |param, value| @progress[param] = value }
end

def valid_date?(year, month, day)
def invalid_date(date_param, day, month, year)
@progress.errors.add(date_param, "is not a valid date")
@progress[date_param] = InvalidDate.new(day:, month:, year:)
end

def invalid_date_range(date_param, field_date)
@progress.errors.add(date_param, "out of range")
@progress[date_param] = field_date
end

def date_out_range?(field_date)
field_date < 12.months.ago || 12.months.from_now > field_date
end

def parse_date(year, month, day)
Date.new(year.to_i, month.to_i, day.to_i)
rescue StandardError
false
nil
end
end
12 changes: 12 additions & 0 deletions spec/validators/application_progress_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,16 @@
end

it_behaves_like "requires a rejection reason"

context "date really out of range" do
let(:date_param) { ApplicationProgressValidator::DATE_PARAMS.first }
let(:params) { { "#{date_param}(3i)" => "31", "#{date_param}(2i)" => "1", "#{date_param}(1i)" => "23" } }

it "adds an error for the invalid date" do
validator = described_class.new(progress, params)

expect(validator.valid?).to be false
expect(progress.errors.details[date_param]).to include(error: "out of range")
end
end
end

0 comments on commit 2d599ae

Please sign in to comment.