From e97a385b237fdb74f1fe74eecf37688679809c33 Mon Sep 17 00:00:00 2001 From: Andreas Maierhofer Date: Tue, 31 Dec 2024 16:38:38 +0100 Subject: [PATCH] Validate swiss zip_code in wizards(#1452) --- app/models/wizards/steps/signup/person_fields.rb | 10 ++++++++++ .../wizards/steps/signup/person_fields_spec.rb | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/app/models/wizards/steps/signup/person_fields.rb b/app/models/wizards/steps/signup/person_fields.rb index 6ec298f31..44d43ed74 100644 --- a/app/models/wizards/steps/signup/person_fields.rb +++ b/app/models/wizards/steps/signup/person_fields.rb @@ -26,6 +26,8 @@ class Wizards::Steps::Signup::PersonFields < Wizards::Step validates :gender, :street, :housenumber, :town, :zip_code, :country, presence: true + validate :assert_is_valid_swiss_post_code + def initialize(...) super @@ -48,4 +50,12 @@ def initialize(...) self.country ||= Settings.addresses.imported_countries.to_a.first end end + + private + + def assert_is_valid_swiss_post_code + if zip_code.present? && Countries.swiss?(country) && !zip_code.to_s.match(/\A\d{4}\z/) + errors.add(:zip_code) + end + end end diff --git a/spec/models/wizards/steps/signup/person_fields_spec.rb b/spec/models/wizards/steps/signup/person_fields_spec.rb index 33dded2be..40b6a6d94 100644 --- a/spec/models/wizards/steps/signup/person_fields_spec.rb +++ b/spec/models/wizards/steps/signup/person_fields_spec.rb @@ -58,6 +58,19 @@ expect(form.errors.full_messages).to eq ["Person muss 6 Jahre oder älter sein"] end end + + describe "zip_code" do + it "validates swiss zip code format" do + form.attributes = required_attrs.merge(zip_code: "123") + expect(form).not_to be_valid + expect(form.errors.full_messages).to eq ["PLZ ist nicht gültig"] + end + + it "accepts any format for non-swiss countries" do + form.attributes = required_attrs.merge(zip_code: "123", country: "DE") + expect(form).to be_valid + end + end end it "sets country default to ch" do