Format numeric sequence in CPF format with separators using javascript

2

The function below tests the input of a cpf, (typing or pasting ) whose format must be ###.###.###-##

If the input consists only of numbers without the separators, or missing some tab, such as ###.######## how can I make the value of the input to be converted to the 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 will exemplify with numbers to be clear

  • When I enter 11111111111 it returns me in the input 111.111.111-11

  • When I enter 111.11111111 it returns me in the input 111.111.111-11

  • When I enter 111.111111-11 it returns me in the input 111.111.111-11

  • etc ...

asked by anonymous 08.07.2017 / 20:15

5 answers

3

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 @J's answer. Guilherme managed 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 involves the exclusion of any digit other than number and test if it returns 11 characters, which assumes that a valid cpf has been entered 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>
    
09.07.2017 / 00:59
1

I've been using regex to do this type of formatting for some time and have been treating 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: link

    
09.07.2017 / 03:03
0

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>
    
08.07.2017 / 22:32
0

I made this script for myself, and it worked. Just remembering, in this case the input was with the attribute maxlength 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 = "___.___.___-__";
}
}
    
13.12.2017 / 20:16
-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");
});
    
08.07.2017 / 20:43