diff --git a/app/models/contact.rb b/app/models/contact.rb index 3b04e6bc1..a63b164bb 100644 --- a/app/models/contact.rb +++ b/app/models/contact.rb @@ -53,7 +53,7 @@ class Contact < ApplicationRecord validates :identifier, allow_blank: true, uniqueness: { scope: [:account_id] } validates :phone_number, allow_blank: true, uniqueness: { scope: [:account_id] }, - format: { with: /\+[1-9]\d{1,14}\z/, message: I18n.t('errors.contacts.phone_number.invalid') } + format: { with: /\A\+[1-9]\d{1,14}\z/, message: I18n.t('errors.contacts.phone_number.invalid') } belongs_to :account has_many :conversations, dependent: :destroy_async @@ -206,7 +206,7 @@ class Contact < ApplicationRecord def phone_number_format return if phone_number.blank? - self.phone_number = phone_number_was unless phone_number.match?(/\+[1-9]\d{1,14}\z/) + self.phone_number = phone_number_was unless phone_number.match?(/\A\+[1-9]\d{1,14}\z/) end def email_format diff --git a/spec/actions/contact_identify_action_spec.rb b/spec/actions/contact_identify_action_spec.rb index 76b370f35..8e91ce0a9 100644 --- a/spec/actions/contact_identify_action_spec.rb +++ b/spec/actions/contact_identify_action_spec.rb @@ -144,6 +144,13 @@ describe ContactIdentifyAction do expect(contact.reload.name).to eq 'new name' expect(contact.phone_number).to be_nil end + + it 'discards a phone number that has text prefixed to a valid number' do + params = { phone_number: 'abc+12312312321', name: 'new name' } + described_class.new(contact: contact, params: params, discard_invalid_attrs: true).perform + expect(contact.reload.name).to eq 'new name' + expect(contact.phone_number).to be_nil + end end context 'when params have not changed' do diff --git a/spec/models/contact_spec.rb b/spec/models/contact_spec.rb index 159454eec..fcd362be8 100644 --- a/spec/models/contact_spec.rb +++ b/spec/models/contact_spec.rb @@ -65,6 +65,11 @@ RSpec.describe Contact do expect { contact.update!(phone_number: '123456789') }.to raise_error(ActiveRecord::RecordInvalid) end + it 'will throw error when text is prefixed to a valid phone number' do + contact = create(:contact) + expect { contact.update!(phone_number: 'abc+12312312321') }.to raise_error(ActiveRecord::RecordInvalid) + end + it 'updates phone number when adding valid phone number' do contact = create(:contact) expect(contact.update!(phone_number: '+12312312321')).to be true