How to validate Cpf with javascript mask?

Asked

Viewed 14,857 times

-1

Guys I’m a beginner in the area and wanted to know how I validate Cpf with javascript mask, I’ve been searching and I couldn’t find one that did both at the same time. I have an example that I had done that in the case the validation was done online, but the site that I used the validation went off the air. From Now Thank You.

<html>
<head>
  <title>Validar CPF com Máscara by TchekiGamer</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="language" content="PT-BR"/>

    <script src="http://www.geradorcpf.com/scripts.js"></script>
    <script src="http://www.geradorcpf.com/jquery-1.2.6.pack.js"></script>
    <script src="http://www.geradorcpf.com/jquery.maskedinput-1.1.4.pack.js"></script>

    </script>

    <script type="text/javascript">$(document).ready(function(){  
      $(".cpf").mask("999.999.999-99");   

      $("#cpf").blur(function (){
        if($("#cpf").val() == '') {           
          $("#saida").html("Informe um CPF");         
          return false;   
        }    
        if(validarCPF($("#cpf").val())) {         
          $(".cpf").css('border-color','limegreen');     
        } 
        else {            
          $(".cpf").css('border-color','red');     
        } 
      });
    });
  </script>
</head>

<body>

  <form id="form1" name="form1" method="post" action="">

    <div align="center" id="saida1">
      <label>Digite o seu cpf</label>
      <input name="cpf" type="text" class="cpf" id="cpf">
    </div>

    <div align="center" id="saida1">
      <label>Teste</label>
      <input name="teste" type="text" class="teste">
    </div>

    <div align="center" id="saida" class="style7"> <!--aparece mensagem de CPF Invalido--> </div>

  </form>
</body>
</html>

3 answers

3


Using our friend’s answer Leo Caracciolo I just added a mask to make it cute as per your request (mask + validator).

function ValidaCPF(){	
	var RegraValida=document.getElementById("RegraValida").value; 
	var cpfValido = /^(([0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2})|([0-9]{11}))$/;	 
	if (cpfValido.test(RegraValida) == true)	{ 
	console.log("CPF Válido");	
	} else	{	 
	console.log("CPF Inválido");	
	}
    }
  function fMasc(objeto,mascara) {
obj=objeto
masc=mascara
setTimeout("fMascEx()",1)
}

  function fMascEx() {
obj.value=masc(obj.value)
}

   function mCPF(cpf){
cpf=cpf.replace(/\D/g,"")
cpf=cpf.replace(/(\d{3})(\d)/,"$1.$2")
cpf=cpf.replace(/(\d{3})(\d)/,"$1.$2")
cpf=cpf.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
return cpf
}
<input type="text" id="RegraValida" value="" name="RegraValida" onkeydown="javascript: fMasc( this, mCPF );"><input type="submit" value="Validar" onclick="ValidaCPF();">

  • Thank you very much Colleague ,helped me a lot, it was exactly what I was needing

1

Likely Error in Your File.

  • Your code will work if you include the missing library, example:
    • <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  • Your file has a </script> more after the file call jquery.maskedinput-1.1.4.pack.js (does not lead to error, however ...)

    To avoid depending on other sites, save the . js files to your server

    or use the script below

Javascript-enabled

Taking advantage of our friend’s reply brnTwp and adding the validation of cpfs according to the IRS rule we have:

function is_cpf (c) {

  if((c = c.replace(/[^\d]/g,"")).length != 11)
    return false

  if (c == "00000000000")
    return false;

  var r;
  var s = 0;

  for (i=1; i<=9; i++)
    s = s + parseInt(c[i-1]) * (11 - i);

  r = (s * 10) % 11;

  if ((r == 10) || (r == 11))
    r = 0;

  if (r != parseInt(c[9]))
    return false;

  s = 0;

  for (i = 1; i <= 10; i++)
    s = s + parseInt(c[i-1]) * (12 - i);

  r = (s * 10) % 11;

  if ((r == 10) || (r == 11))
    r = 0;

  if (r != parseInt(c[10]))
    return false;

  return true;
}


function fMasc(objeto,mascara) {
obj=objeto
masc=mascara
setTimeout("fMascEx()",1)
}

  function fMascEx() {
obj.value=masc(obj.value)
}

function mCPF(cpf){
cpf=cpf.replace(/\D/g,"")
cpf=cpf.replace(/(\d{3})(\d)/,"$1.$2")
cpf=cpf.replace(/(\d{3})(\d)/,"$1.$2")
cpf=cpf.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
return cpf
}

cpfCheck = function (el) {
    document.getElementById('cpfResponse').innerHTML = is_cpf(el.value)? '<span style="color:green">válido</span>' : '<span style="color:red">inválido</span>';
    if(el.value=='') document.getElementById('cpfResponse').innerHTML = '';
}
<p>Digite o CPF:</p>
<p><input id="cpf" type="text" onkeyup="cpfCheck(this)" maxlength="18" onkeydown="javascript: fMasc( this, mCPF );"> <span id="cpfResponse"></span></p>

  • Hello I just tested your code and just put a Cpf for example 444.444.444-44 and this is wrong and do not know what to do

  • @Guilhermehenrique, see that in the answer I highlighted e acrescentando a validação de cpfs segundo a regra da receita federal, therefore, this Cpf 444.444.444-44, According to the IRS, It’s not a valid CPF. Who cares about an invalid CPF? My answer beyond the mask only accepts really valid Cpfs, unlike the answers

  • is showing value for 444.444.444-44

0

You can let the guy type in the numbers without putting in the dots and then replace it with the code below.

function replaceCPF(cpf){
  return cpf.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
}

Browser other questions tagged

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