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.
This commit is contained in:
Pierre de La Morinerie 2022-03-01 16:45:44 +01:00 committed by Paul Chavard
parent f35d18cd5c
commit e32c9a9f94
2 changed files with 14 additions and 1 deletions

View file

@ -50,6 +50,13 @@ class Champs::PhoneChamp < Champs::TextChamp
def to_s
return '' if value.blank?
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

View file

@ -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)