From 6cb6c2f81ca0fcbdb16d1698e0d2759c1cc05d41 Mon Sep 17 00:00:00 2001 From: natdeanlewissoftwire Date: Tue, 29 Nov 2022 15:43:24 +0000 Subject: [PATCH] feat: add date model validation --- app/controllers/locations_controller.rb | 8 ++++++-- app/models/location.rb | 8 ++++++++ config/locales/en.yml | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/app/controllers/locations_controller.rb b/app/controllers/locations_controller.rb index c2e7bdb11..f06d9b89f 100644 --- a/app/controllers/locations_controller.rb +++ b/app/controllers/locations_controller.rb @@ -132,8 +132,12 @@ class LocationsController < ApplicationController if [day, month, year].none?(&:blank?) if Date.valid_date?(year.to_i, month.to_i, day.to_i) @location.startdate = Time.zone.local(year.to_i, month.to_i, day.to_i) - @location.save! - redirect_to scheme_location_check_answers_path(@scheme, @location) + if @location.valid?(:startdate) + @location.save! + redirect_to scheme_location_check_answers_path(@scheme, @location) + else + render :availability, status: :unprocessable_entity + end else error_message = I18n.t("validations.location.startdate_invalid") @location.errors.add :startdate, error_message diff --git a/app/models/location.rb b/app/models/location.rb index 263cb7b8a..230bb182e 100644 --- a/app/models/location.rb +++ b/app/models/location.rb @@ -5,6 +5,7 @@ class Location < ApplicationRecord validate :validate_units, on: :units validate :validate_type_of_unit, on: :type_of_unit validate :validate_mobility_type, on: :mobility_type + validate :validate_startdate, on: :startdate belongs_to :scheme has_many :lettings_logs, class_name: "LettingsLog" has_many :location_deactivation_periods, class_name: "LocationDeactivationPeriod" @@ -442,6 +443,13 @@ class Location < ApplicationRecord end end + def validate_startdate + unless startdate.between?(Time.zone.local(1900, 1, 1), Time.zone.local(2200, 1, 1)) + error_message = I18n.t("validations.location.startdate_out_of_range") + errors.add :startdate, error_message + end + end + private PIO = PostcodeService.new diff --git a/config/locales/en.yml b/config/locales/en.yml index 6516ca1aa..ae226ffd7 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -332,6 +332,7 @@ en: mobility_standards: "Select the mobility standard for the majority of the units at this location" startdate_blank: "Enter the day, month and year when the first property became available at this location" startdate_invalid: "Enter a valid day, month and year" + startdate_out_of_range: "Availability date must be between 1900 and 2200" toggle_date: not_selected: "Select one of the options" invalid: "Enter a valid day, month and year"