Input mask for CPF in html form (without plugin)

1

I wanted a simple input mask, just to put 999.999.999-99, dots and the last dash in the cpf field, no verification, no nothing, simple, and no code only plugin, if I am not mistaken have the regrex or something similar, I appreciate the attention!

    
asked by anonymous 11.04.2018 / 16:37

1 answer

2

You can use this, but only works with blur :

var cpf = document.querySelector("#cpf");

cpf.addEventListener("blur", function(){
   if(cpf.value) cpf.value = cpf.value.match(/.{1,3}/g).join(".").replace(/\.(?=[^.]*$)/,"-");
});
<input type="text" id="cpf" maxlength="11" />

This also works while the CPF is being typed:

function mascara(i){
   
   var v = i.value;
   
   if(isNaN(v[v.length-1])){ // impede entrar outro caractere que não seja número
      i.value = v.substring(0, v.length-1);
      return;
   }
   
   i.setAttribute("maxlength", "14");
   if (v.length == 3 || v.length == 7) i.value += ".";
   if (v.length == 11) i.value += "-";

}
<input oninput="mascara(this)" type="text">
    
11.04.2018 / 16:47