Format numerical sequence in CPF format with tabs using javascript

Asked

Viewed 21,461 times

6

The function below tests the input of a Cpf, (typing or gluing) whose format should be ###.###.###-##

If the input consists only of numbers without separators, or some separator is missing, for example ###.######## how can I make value input is converted to valid format.

is not CPF validation but pure formatting!!!

function ValidaCPF(){   

    var ao_cpf=document.forms.form1.ao_cpf.value; 
    var cpfValido = /^(([0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}))$/;     
    if (cpfValido.test(ao_cpf) == false)    {  
       //alert("invalido");
       var valorValido = document.getElementById("ao_cpf").value = "???????";
    }
}
<form name="form1">
<input type="text" name="ao_cpf" id="ao_cpf" placeholder="CPF" maxlength="14" OnBlur="ValidaCPF();"/>
</form>

I’ll illustrate with numbers to be clear

  • on entering 11111111111 return me to input 111.111.111-11

  • on entering 111.11111111 return me to input 111.111.111-11

  • on entering 111.111111-11 return me to input 111.111.111-11

  • etc....

  • you want to validate the amount of numbers tbm?

6 answers

18

I’ve been using regex to do this type of formatting for some time and it has served me well.

var cpf = "00000000000";

return console.log(formataCPF(cpf));

function formataCPF(cpf){
  //retira os caracteres indesejados...
  cpf = cpf.replace(/[^\d]/g, "");

  //realizar a formatação...
    return cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
}

I have prepared a solution proposal in jsfiddle. Follow the link: https://jsfiddle.net/hye31ufr/1/

  • simple and works great! thanks!

6


Due to @Everson’s comment

Este código da resposta funciona, porém, se não está na formatação exata de 11 dígitos não vai funcionar mesmo

in the @J. Guilherme response I was able to make the code work.

function ValidaCPF(){   

var ao_cpf=document.forms.form1.ao_cpf.value; 
var cpfValido = /^(([0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}))$/;     
if (cpfValido.test(ao_cpf) == false)    { 
     
   ao_cpf = ao_cpf.replace( /\D/g , ""); //Remove tudo o que não é dígito
		    
   if (ao_cpf.length==11){
	  ao_cpf = ao_cpf.replace( /(\d{3})(\d)/ , "$1.$2"); //Coloca um ponto entre o terceiro e o quarto dígitos
	  ao_cpf = ao_cpf.replace( /(\d{3})(\d)/ , "$1.$2"); //Coloca um ponto entre o terceiro e o quarto dígitos
	  //de novo (para o segundo bloco de números)
	  ao_cpf = ao_cpf.replace( /(\d{3})(\d{1,2})$/ , "$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
			    
	  var valorValido = document.getElementById("ao_cpf").value = ao_cpf;
	}else{
	  console.log("CPF invalido");
	}
		
}
}
<form name="form1">
<input type="text" name="ao_cpf" id="ao_cpf" placeholder="CPF" maxlength="14" OnBlur="ValidaCPF();"/>
</form>

the X of the question goes through the exclusion of any digit that is not a number and test whether it returns 11 characters, which supposes that a valid Cpf was inserted but without the expected formatting.

function ValidaCPF(){   
  var ao_cpf=document.forms.form1.ao_cpf.value; 
  var cpfValido = /^(([0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}))$/;     
  ao_cpf = ao_cpf.replace( /(\d{3})(\d)/ , "$1.$2"); //Coloca um ponto entre o terceiro e o quarto dígitos
  ao_cpf = ao_cpf.replace( /(\d{3})(\d)/ , "$1.$2"); //Coloca um ponto entre o terceiro e o quarto dígitos
  //de novo (para o segundo bloco de números)
  ao_cpf = ao_cpf.replace( /(\d{3})(\d{1,2})$/ , "$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
			    
  var valorValido = document.getElementById("ao_cpf").value = ao_cpf;
}
<form name="form1">
<input type="text" name="ao_cpf" id="ao_cpf" placeholder="CPF" maxlength="14" OnBlur="ValidaCPF();"/>
</form>

1

Edit your function as follows:

function ValidaCPF(){   

    var ao_cpf=document.forms.form1.ao_cpf.value; 
    if(ao_cpf.match(/\d/g).join('').length === 11) { 
        console.log('cpf invalido.'); 
        return;
    }
    var cpfValido = /^(([0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}))$/;     
    if (cpfValido.test(ao_cpf) == false)    {  
       //alert("invalido");
       var formattedCpf = ao_cpf.replace(/^(\d{3})\D*(\d{3})\D*(\d{3})\D*(\d{2})$/g,'$1.$2.$3-$4');
       var valorValido = document.getElementById("ao_cpf").value = formattedCpf;
    }
}
<form name="form1">
<input type="text" name="ao_cpf" id="ao_cpf" placeholder="CPF" maxlength="14" OnBlur="ValidaCPF();"/>
</form>

  • Could someone explain to me why my answer was negative?

  • I was not the one who said no, ideally you would post a complete and/or executable reply.

  • i edited my post in order to make the function clearer

  • It is, reading the code seems all right and that it should work but like the others, that also seem correct, that I’ve been experimenting, does not give return

  • This response code works, however, if it is not in the exact 11 digit formatting will not work even.

  • @Exact everson, limiting the input to 11 digits will give problem when typing the correct Cpf manually

  • @Everson, that remark of yours lit the lamps in my brain and led me to the answer to my question!!!!!!

  • I was in doubt if I had to validate the size of the number, so I asked in the comments of the question... but I’m glad it worked out in the end! ps: I edited my answer validating the size of the tbm, to make it complete

Show 3 more comments

0

I made this script for myself, and it worked. Just remember, in this case the input was with the maxlength attribute value 15.

document.getElementById('CPF').value = "___.___.___-__";
function validateCPF(){
var CPF = document.getElementById('CPF').value;
var auxCPF = true;
var cpf = [];
for (var i = 0; i < CPF.length; i++) {
    cpf.push(CPF[i]);
    if(i != 3 && i != 7 && i != 11){
        if (CPF[i] != '0' && CPF[i] != '1' && CPF[i] != '2' && CPF[i] != '3' && CPF[i] != '4' && CPF[i] != '5' && CPF[i] != '6' && CPF[i] != '7' && CPF[i] != '8' && CPF[i] != '9' && CPF != "___.___.___-_") {
            auxCPF = false;
            cpf.splice(i, 1,);
        }else if(auxCPF == true){
            auxCPF == true;
            s_CPF.innerHTML = '';
        }
    }
    if(cpf.length < CPF.length){
        if(i == 2 && CPF[3] != "."){
            cpf.splice(3, 0, ".");
            console.log(cpf);
        }
        if(i == 6 && CPF[7] != "."){
            cpf.splice(7, 0, ".");
            console.log(cpf);
        }
        if(i == 10 && CPF[11] != "-"){
            cpf.splice(11, 0, "-");
            console.log(cpf);
        }
    }
}
lastCPF = "";
for (var i = 0; i < cpf.length; i++) {
    if((cpf[i] == "." && i != 3 && i != 7) || (cpf[i] == "-" && i != 11) || cpf[i] == "_" || cpf[i] == " "  || i < 14 && (i != 11 && i != 3 && i != 7 && cpf[i] != '0' && cpf[i] != '1' && cpf[i] != '2' && cpf[i] != '3' && cpf[i] != '4' && cpf[i] != '5' && cpf[i] != '6' && cpf[i] != '7' && cpf[i] != '8' && cpf[i] != '9') || i > 13){
        cpf.splice(i,1,"");
        console.log(cpf);
    }
    lastCPF += cpf[i];
}
document.getElementById('CPF').value = lastCPF;
if(document.getElementById('CPF').value == ""){
    document.getElementById('CPF').value = "___.___.___-__";
}
}

0

Small improvement in the example with regex with tolerance to nulos or undefined

function formatCpf(text) {
    const badchars = /[^\d]/g
    const mask = /(\d{3})(\d{3})(\d{3})(\d{2})/
    const cpf = new String(text).replace(badchars, "");
    return cpf.replace(mask, "$1.$2.$3-$4");
  }

-1

"Try this"

function cpfCnpj(v,label){

    //CNPJ
    if (label == 'J'){
        return formataCampo(v, '00.000.000/0000-00', event);
    }
    //CPF
    if (label == 'F'){
        return formataCampo(v, '000.000.000-00', event);
    }

}
//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) { 
    var boleanoMascara; 

    var Digitato = evento.keyCode;
    exp = /\-|\.|\/|\(|\)| /g
    campoSoNumeros = campo.value.toString().replace( exp, "" ); 

    var posicaoCampo = 0;     
    var NovoValorCampo="";
    var TamanhoMascara = campoSoNumeros.length;; 

    if (Digitato != 8) { // backspace 
        for(i=0; i<= TamanhoMascara; i++) { 
            boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                || (Mascara.charAt(i) == "/")) 
            boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(") 
                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " ")) 
            if (boleanoMascara) { 
                NovoValorCampo += Mascara.charAt(i); 
                  TamanhoMascara++;
            }else { 
                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); 
                posicaoCampo++; 
              }            
          }     
        campo.value = NovoValorCampo;
          return true; 
    }else { 
        return true; 
    }
}

//Ou ainda em Jquery

$(function($){
   $("#cpf").mask("999.999.999-99");
   $("#cnpj").mask("99.999.999/9999-99");
});

  • look at the tag, javascript

  • forgot ! sorry helped ?

  • was worth the effort, but I would like to pass to the variable valuedValido the format valid inside that function

Browser other questions tagged

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