From bf7c81592dbe810a551404a51c13158ea1044437 Mon Sep 17 00:00:00 2001 From: baarkerlounger <5101747+baarkerlounger@users.noreply.github.com> Date: Fri, 12 Aug 2022 14:24:48 +0100 Subject: [PATCH] More robust date validation (#830) * More robust date validation * Update app/controllers/form_controller.rb Co-authored-by: James Rose Co-authored-by: James Rose --- app/controllers/form_controller.rb | 2 +- spec/requests/form_controller_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/app/controllers/form_controller.rb b/app/controllers/form_controller.rb index ad3f858e3..52e3bc3a7 100644 --- a/app/controllers/form_controller.rb +++ b/app/controllers/form_controller.rb @@ -89,7 +89,7 @@ private year = params["case_log"]["#{question.id}(1i)"] next unless [day, month, year].any?(&:present?) - result[question.id] = if day.to_i.between?(1, 31) && month.to_i.between?(1, 12) && year.to_i.between?(2000, 2200) + result[question.id] = if Date.valid_date?(year.to_i, month.to_i, day.to_i) && year.to_i.between?(2000, 2200) Date.new(year.to_i, month.to_i, day.to_i) else Date.new(0, 1, 1) diff --git a/spec/requests/form_controller_spec.rb b/spec/requests/form_controller_spec.rb index 7bad7b0a3..4be3f5c03 100644 --- a/spec/requests/form_controller_spec.rb +++ b/spec/requests/form_controller_spec.rb @@ -255,6 +255,27 @@ RSpec.describe FormController, type: :request do expect(Rails.logger).to receive(:info).with("User triggered validation(s) on: age1").once post "/logs/#{case_log.id}/form", params: params end + + context "when the number of days is too high for the month" do + let(:page_id) { "tenancy_start_date" } + let(:params) do + { + id: case_log.id, + case_log: { + page: page_id, + "startdate(3i)" => 31, + "startdate(2i)" => 6, + "startdate(1i)" => 2022, + }, + } + end + + it "validates the date correctly" do + post "/logs/#{case_log.id}/form", params: params + follow_redirect! + expect(page).to have_content("There is a problem") + end + end end context "with valid answers" do