diff --git a/app/javascript/app/modules/international-phone-formatter.js b/app/javascript/app/modules/international-phone-formatter.js index 2b3ee0b47db..6f4376a3a46 100644 --- a/app/javascript/app/modules/international-phone-formatter.js +++ b/app/javascript/app/modules/international-phone-formatter.js @@ -1,6 +1,8 @@ import { Formatter } from 'field-kit'; import { asYouType as AsYouType } from 'libphonenumber-js'; +const INTERNATIONAL_CODE_REGEX = /^\+\d{1,3} /; + const fixCountryCodeSpacing = (text, countryCode) => { // If the text is `+123456`, make it `+123 456` if (text[countryCode.length + 1] !== ' ') { @@ -29,6 +31,15 @@ const getFormattedTextData = (text) => { }; }; +const changeRemovesInternationalCode = (current, previous) => { + if (previous.text.match(INTERNATIONAL_CODE_REGEX) && + !current.text.match(INTERNATIONAL_CODE_REGEX) + ) { + return true; + } + return false; +}; + const cursorPosition = (formattedTextData) => { // If the text is `(23 )` the cursor goes after the 3 const match = formattedTextData.text.match(/\d[^\d]*$/); @@ -53,10 +64,7 @@ class InternationalPhoneFormatter extends Formatter { const formattedTextData = getFormattedTextData(change.proposed.text); const previousFormattedTextData = getFormattedTextData(change.current.text); - if (previousFormattedTextData.template && - !formattedTextData.template && - change.inserted.text.length === 1 - ) { + if (changeRemovesInternationalCode(formattedTextData, previousFormattedTextData)) { return false; } diff --git a/spec/features/two_factor_authentication/sign_in_spec.rb b/spec/features/two_factor_authentication/sign_in_spec.rb index afe7918bb1c..593cea03382 100644 --- a/spec/features/two_factor_authentication/sign_in_spec.rb +++ b/spec/features/two_factor_authentication/sign_in_spec.rb @@ -143,6 +143,26 @@ expect(find('#user_phone_form_phone').value).to include '+81' end + + scenario 'does not allow the user to remove the international code after entering it', :js do + sign_in_before_2fa + fill_in 'Phone', with: '+81 54 354 3643' + + input = find('#user_phone_form_phone') + input.send_keys(*([:backspace] * input.value.length)) + + expect(input.value).to eq('+81 ') + end + + scenario 'allows a user to continue typing even if a number is invalid', :js do + sign_in_before_2fa + select 'United States of America +1', from: 'International code' + + input = find('#user_phone_form_phone') + input.send_keys('12345678901234567890') + + expect(input.value).to eq('+1 2345678901234567890') + end end end