'Phone mask for text field with regex

I'm using this function to phone mask and works almost perfectly.

function mask(o, f) 
{ 
    v_obj = o; 
    v_fun = f; 
    setTimeout("execmask()", 1) 
};

function execmask() 
{ 
    v_obj.value = v_fun(v_obj.value) 
};

function mphone(v){
    v=v.replace(/\D/g,"");           
    v=v.substring(0, 11);
    v=v.replace(/^(\d{2})(\d)/g,"(OXX$1) $2"); 
    v=v.replace(/(\d)(\d{4})$/,"$1-$2"); 
    return v;
}

Here I run the mask in the text field:

<input type="text" id="phone" name="phone" onkeypress="mask(this, mphone);" onblur="mask(this, mphone);" />

The problem is that I need to change this part of the code (OXX$1) to (0XX$1).

Current situation:

No. Of Digits Input Field
9 digit (OXX99) 99999-9999
8 digit (OXX99) 9999-9999

The correct formatting that I need:

No. Of Digits Input Field
9 digit (0XX99) 99999-9999
8 digit (0XX99) 9999-9999

The amount of 8 or 9 digits is the choice of the user.

Changing O to 0, causes an error in the mask.



Solution 1:[1]

In this sandbox project it is possible to see the use of the methods below, applying them in an input: https://codesandbox.io/s/epic-darwin-obj8dp

Regex masks:


// 10.000,00
const maskMoney = (event) => {
  const { value } = event.currentTarget;
  return value
    .replace(/\D/g, '')
    .replace(/(\d)(\d{2})$/, '$1,$2')
    .replace(/(?=(\d{3})+(\D))\B/g, '.');
};

// 000.000.000-00
const maskCPF = (event) => {
  event.currentTarget.maxLength = 15;
  const { value } = event.currentTarget;

  return value
    .replace(/\D/g, '')
    .replace(/(\d{3})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d{1,2})/, '$1-$2')
    .replace(/(-\d{2})\d+?$/, '$1');
};

// 00.000.000/0000-000
const maskCNPJ = (event) => {
  event.currentTarget.maxLength = 18;
  const { value } = event.currentTarget;
  return value
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d)/, '$1/$2')
    .replace(/(\d{4})(\d{2})/, '$1-$2');
};

// 000.000.000-00 or 00.000.000/0000-000
const maskCPFOrCNPJ = (event) => {
  event.currentTarget.maxLength = 18;
  const { value } = event.currentTarget;
  if (value.length >= 15) {
    return maskCNPJ(event);
  }
  return maskCPF(event);
};

// (00) 00000-0000
const maskPhone = (event) => {
  event.currentTarget.maxLength = 15;
  const { value } = event.currentTarget;
  return value
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '($1) $2')
    .replace(/(\d{5})(\d{4})/, '$1-$2');
};

// (00) 0000-0000
const maskLandlineTelephone = (
  event,
) => {
  event.currentTarget.maxLength = 14;
  const { value } = event.currentTarget;
  return value
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '($1) $2')
    .replace(/(\d{4})(\d{4})/, '$1-$2');
};

// 00000-000
const maskCEP = (event) => {
  event.currentTarget.maxLength = 9;
  const { value } = event.currentTarget;
  return value.replace(/\D/g, '').replace(/^(\d{5})(\d{3})+?$/, '$1-$2');
};

// 00/00/0000
const maskDate = (event) => {
  event.currentTarget.maxLength = 10;
  const { value } = event.currentTarget;
  return value
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '$1/$2')
    .replace(/(\d{2})(\d)/, '$1/$2')
    .replace(/(\d{4})(\d)/, '$1');
};

const maskOnlyLetters = (event) => {
  const { value } = event.currentTarget;
  return value.replace(/[0-9!@#¨$%^&*)(+=._-]+/g, '');
};

const maskOnlyNumbers = (event) => {
  const { value } = event.currentTarget;
  return value.replace(/\D/g, '');
};

Solution 2:[2]

I have made some changes:

  1. I changed the event to keyup (besides the fact that keypress has been deprecated) because keypress always takes the string with one less character and to work I also needed onblur, something that doesn't happen with keyup. Code adjustments were needed to resolve this
  2. and the issue of the "-", that when tried to remove it with backspace it kept always coming back.

fiddle

  function mascaraFone(event) {
    var valor = document.getElementById("telefone").attributes[0].ownerElement['value'];
    var retorno = valor.replace(/\D/g, "");
    retorno = retorno.replace(/^0/, "");
    if (retorno.length > 10) {
      retorno = retorno.replace(/^(\d\d)(\d{5})(\d{4}).*/, "($1) $2-$3");
    } else if (retorno.length > 5) {
      if (retorno.length == 6 && event.code == "Backspace") { 
        // necessário pois senão o "-" fica sempre voltando ao dar backspace
        return; 
      } 
      retorno = retorno.replace(/^(\d\d)(\d{4})(\d{0,4}).*/, "($1) $2-$3");
    } else if (retorno.length > 2) {
      retorno = retorno.replace(/^(\d\d)(\d{0,5})/, "($1) $2");
    } else {
      if (retorno.length != 0) {
        retorno = retorno.replace(/^(\d*)/, "($1");
      }
    }
    document.getElementById("telefone").attributes[0].ownerElement['value'] = retorno;
  }
<input id="telefone" onkeyup="mascaraFone(event)" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcos Santos Dev
Solution 2 Gangula