Skip to content

Instantly share code, notes, and snippets.

@brunotdantas
Created November 21, 2022 19:29
Show Gist options
  • Save brunotdantas/c7662a4dacb502948e8ce5c7b6dd90e5 to your computer and use it in GitHub Desktop.
Save brunotdantas/c7662a4dacb502948e8ce5c7b6dd90e5 to your computer and use it in GitHub Desktop.
Validate CPF (BR GOVERNMENT UNIQUE ID)
// source: https://www.devmedia.com.br/validar-cpf-com-javascript/23916
function TestaCPF(strCPF) {
var Soma;
var Resto;
Soma = 0;
if (strCPF == "00000000000") return false;
for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i);
Resto = (Soma * 10) % 11;
if ((Resto == 10) || (Resto == 11)) Resto = 0;
if (Resto != parseInt(strCPF.substring(9, 10)) ) return false;
Soma = 0;
for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i);
Resto = (Soma * 10) % 11;
if ((Resto == 10) || (Resto == 11)) Resto = 0;
if (Resto != parseInt(strCPF.substring(10, 11) ) ) return false;
return true;
}
var strCPF = "12345678909";
alert(TestaCPF(strCPF));// false = invalid CPF
var strCPF2 = "56801154095";
// if you need more CPFs: https://www.4devs.com.br/gerador_de_cpf
alert(TestaCPF(strCPF2));// true = valid CPF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment