rodrigosantosbr

[JS] CPF validation

Jan 17th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

http://jsbin.com/?html,js,output


html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  cpf: <input type="text" id="cpf"/><br/>
  <input type=button onclick="submeter()" value="Data">
</body>
</html>

javascript

function submeter(){
  cpf = document.getElementById("cpf").value;
  cpf = cpf.replace(/\./g, "");
  cpf = cpf.replace(/-/g, "");
  validar = validarCPF(cpf);
  alert(validar);
}
function validarCPF(cpf)
{
   if(cpf.length != 11 || cpf.replace(eval('/'+cpf.charAt(1)+'/g'),'') == '')
   {
      return false;
   }
   else
   {
      for(n=9; n<11; n++)
      {
         for(d=0, c=0; c<n; c++) d += cpf.charAt(c) * ((n + 1) - c);
         d = ((10 * d) % 11) % 10;
         if(cpf.charAt(c) != d) return false;
      }
      return true;
   }
}
Add Comment
Please, Sign In to add comment