How do I put a mask on a Bank Account input in JS?

Asked

Viewed 1,418 times

0

I need to create a mask to hyphenate the penultimate number, automatically, as long as it has at least 5 characters, in a bank account input, using pure JS. Thus: xxxx-x | xxxxx-x | xxxxxx-x.

<div class="form-group" align="center">
   <label for="cc-nome">Número da conta</label>
   <input type="text" class="line-animation" placeholder="" name="conta"  value="0000-0" required>
   <div class="line"></div>
</div>

1 answer

0

I resolved it as follows:

function FormataDado(campo, tammax, pos, teclapres) {   
  var keyCode; 
  if (teclapres.srcElement) 
  {
    keyCode = teclapres.keyCode; 
  } else  if (teclapres.target) 
  {
  keyCode = teclapres.which; 
  }
  if (keyCode == 0 || keyCode == 8) { return true; }  
  if ((keyCode < 48 || keyCode > 57) && keyCode != 88 && (keyCode != 120)) { return false; }  
  var tecla = keyCode; 
  vr = campo.value;   
  vr = vr.replace("-", "");   
  vr = vr.replace("/", ""); 
  
  tam = vr.length;
  if (tam < tammax && tecla != 8) 
  { tam = vr.length + 1; } 
  if (tecla == 8) 
{
    tam = tam - 1; 
}
  if (tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 || tecla == 120) 
{
  if (tam <= 2) 
{
      campo.value = vr; 
}
  if (tam > pos && tam <= tammax) 
{
campo.value = vr.substr(0, tam - pos) + "-" + vr.substr(tam - pos, tam); 
}
}
}
<input type="text" class="line-animation" placeholder="" name="conta" id="ContaB" value="0000" required onkeypress="return FormataDado(this,12,1,event);"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.