From e32c9a9f94e88321003d4b615804da49c957bed2 Mon Sep 17 00:00:00 2001 From: Pierre de La Morinerie Date: Tue, 1 Mar 2022 16:45:44 +0100 Subject: [PATCH] models: don't attempt to format invalid phone numbers This is a defensive-programming measure, because formatting an invalid phone number may truncate some leading numbers. --- app/models/champs/phone_champ.rb | 9 ++++++++- spec/models/champs/phone_champ_spec.rb | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/app/models/champs/phone_champ.rb b/app/models/champs/phone_champ.rb index ae06abe14..ac2c51449 100644 --- a/app/models/champs/phone_champ.rb +++ b/app/models/champs/phone_champ.rb @@ -50,6 +50,13 @@ class Champs::PhoneChamp < Champs::TextChamp def to_s return '' if value.blank? - Phonelib.parse_for_countries(value, DEFAULT_COUNTRY_CODES).full_national + + if Phonelib.valid_for_countries?(value, DEFAULT_COUNTRY_CODES) + Phonelib.parse_for_countries(value, DEFAULT_COUNTRY_CODES).full_national + else + # When he phone number is possible for the default countries, but not strictly valid, + # `full_national` could mess up the formatting. In this case just return the original. + value + end end end diff --git a/spec/models/champs/phone_champ_spec.rb b/spec/models/champs/phone_champ_spec.rb index df7e9095a..275986c33 100644 --- a/spec/models/champs/phone_champ_spec.rb +++ b/spec/models/champs/phone_champ_spec.rb @@ -52,6 +52,12 @@ describe Champs::PhoneChamp do expect(champ_with_value("45187272").to_s).to eq("45187272") end end + + context 'for possible (but not valid) phone numbers' do + it 'returns the original' do + expect(champ_with_value("1234").to_s).to eq("1234") + end + end end def champ_with_value(number)