CaioQuirinoMedeiros / react-native-mask-input

🎭:iphone: A simple and effective Text Input with mask for ReactNative on iOS and Android. Includes obfuscation characters feature.
https://www.npmjs.com/package/react-native-mask-input
MIT License
304 stars 31 forks source link

Toggle phone mask for 8 or 9 digits #22

Open gabrielamarques opened 2 years ago

gabrielamarques commented 2 years ago

I'd like the phone mask to toggle: landline x mobile phones (just like cpf/cnpj). (xx) xxxx - xxxx and (xx) xxxxx - xxxx

Currently a 8-digit phone is masked like: (xx) xxxxx - xxx

CaioQuirinoMedeiros commented 2 years ago

@gabrielamarques use a function to return a mask based on the input, here is an example (not tested):

<MaskInput
  mask={(text: string) => {
    const cleanNumber = text.replace(/\D+/g, '')

    if (cleanNumber.length < 9) {
      return ["(", /\d/, /\d/, ")", " ", /\d/, /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/, /\d/,]
    } else {
      return ["(", /\d/, /\d/, ")", " ", /\d/, /\d/, /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/,]
    }
  }}
  ...
/>
RodolfoSilva commented 1 year ago

Thanks @CaioQuirinoMedeiros

The snippet above is always usign the second format.

I've made some changes to support both format:

const BRL_PHONE_SHORT = ["(", /\d/, /\d/, ")", " ", /\d/, /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/, /\d/,];
const BRL_PHONE_LONG = ["(", /\d/, /\d/, ")", " ", /\d/, /\d/, /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/,];

const mask = (text?: string) => {
  const sanitizedText = text?.replace(/\D/g, "") ?? "";
  return sanitizedText.length < 11 ? BRL_PHONE_SHORT : BRL_PHONE_LONG;
};

This now supports: