Skip to content

Instantly share code, notes, and snippets.

@franciscojsc
Last active March 19, 2022 16:17
Show Gist options
  • Save franciscojsc/bdb823f42add68ca9a51f3aabe869c18 to your computer and use it in GitHub Desktop.
Save franciscojsc/bdb823f42add68ca9a51f3aabe869c18 to your computer and use it in GitHub Desktop.
Verificador de CPF em JavaScript
/*
* Fonte: https://www.devmedia.com.br/validar-cpf-com-javascript/23916 (Em Português)
* https://forum.imasters.com.br/topic/140772-resolvido-validar-cpf/ (Em Português)
*
* Função adaptada por Francisco Chaves <[email protected]>
*
* CPF correto retorna true, senão false.
*/
function verifyCPF(cpf) {
let sum = 0;
let rest = 0;
let { cpfValid, isValid } = validFormatCPF(cpf);
if (!isValid) return false;
for (i = 1; i <= 9; i++) {
sum = sum + parseInt(cpfValid.substring(i - 1, i)) * (11 - i);
}
rest = (sum * 10) % 11;
if (rest == 10 || rest == 11) rest = 0;
if (rest != parseInt(cpfValid.substring(9, 10))) return false;
sum = 0;
for (i = 1; i <= 10; i++) {
sum = sum + parseInt(cpfValid.substring(i - 1, i)) * (12 - i);
}
rest = (sum * 10) % 11;
if (rest == 10 || rest == 11) rest = 0;
if (rest != parseInt(cpfValid.substring(10, 11))) return false;
return true;
}
const validFormatCPF = (cpf) => {
const regexValidCPF = /^\d{3}\.?\d{3}\.?\d{3}\-?\d{2}$/;
if (!cpf.match(regexValidCPF)) {
return {
cpfValid: cpf,
isValid: false,
};
}
// Remove pontos e traços do CPF
cpf = cpf.replace('-', '').replace(/\./g, '');
// Verifica se o CPF possui números repetidos (ex: 111.111.111-11)
if (cpf.match(/^(\d)\1{10}/g)) {
return {
cpfValid: cpf,
isValid: false,
};
}
return { cpfValid: cpf, isValid: true };
};
@rafael-feitosa
Copy link

Olá, Chico!

Consigo validar um campo de cpf em um formulário de wordpress com esse código?

@franciscojsc
Copy link
Author

Olá amigo!

Consegue sim, você precisa adicionar o script no head ou antes de fechar o body da página, e utilizando o evento de onfocusout podemos capturar o momento que o usuário tira o foco do campo de entrada para realizar a validação.

Exemplo:

<!DOCTYPE html>
<html lang="pt-BR">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Formulário</title>
  </head>
  <body>
    <input type="text" id="cpf" />

    <script src="./test-cpf.js"></script>

    <script>
      const cpf = document.getElementById('cpf');
      cpf.addEventListener('focusout', function () {
        const cpf = document.getElementById('cpf').value;
        if (verifyCPF(cpf)) {
          alert('CPF Válido');
        } else {
          alert('CPF Inválido');
        }
      });
    </script>
  </body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment