libphonenumber-js: Can not delete phone number in US National format when the input string has 3 characters

I’m using AsYouType to format the input phone number, I got an error when attempting to delete phone number by press Backspace when the input string has 3 characters.

Check out the gif and the code below: asyoutype-error

new AsYouType('US').input(value)

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 6
  • Comments: 15 (2 by maintainers)

Commits related to this issue

Most upvoted comments

I am was looking for an answer but don’t really like to start applying AsYouType after 3 digits… Here is what I came up with, hope it helps others:

export const formatPhoneNumber = (value?: string | number) => {
    if (!value) return '';
    value = value.toString();
    if (value.includes('(') && !value.includes(')')) {
        return value.replace('(', '');
    }
    return new AsYouType('US').input(value);
};

This is kind of a helper function I use to include in input onchange if input type is phone

@nguyennb9 I was able to work around this by only formatting once the character count is over 3 digits. What I believe to be happening is that when you hit the backspace, the field is still evaluating to 3 digits which will add the parenthesis for US format. Adding in a conditional to start formatting after 3 digits have been entered worked well for me.

Yeah, the code comment has the well explained here..

@whimsicaldreamer And with AsYouType, you only apply it when the input contains more than 3 characters, maybe this regex /(.?\d){4,}/.test(input) will help you detect when to start applying AsYouType. Nothing to format with just 3 numbers isn’t?

I wasn’t super happy with any of the solutions here, so here’s what I ended up doing. Hopefully this helps someone out 😃

import {
  formatIncompletePhoneNumber,
} from 'libphonenumber-js';

...

// onChangeText is a react-native TextInput thing fyi
const _onChangeText = (text: string) => {
  let formattedPhoneNumber = formatIncompletePhoneNumber(text, countryCode);
  // Handle delete
  if (formattedPhoneNumber === props.value) {
    const digits = formattedPhoneNumber.replace(/\D/g,''); //strip away non-numeric characters
    const withoutLastDigit = digits.slice(0, digits.length - 1); //remove the last digit
    formattedPhoneNumber = formatIncompletePhoneNumber(withoutLastDigit, countryCode);
  }
  onChangeText(formattedPhoneNumber);
};

@jharsono I am hesitant to hardcode 3 because I don’t know how other countries format their phone numbers. Is the US the only country using parentheses?