Skip to content

Instantly share code, notes, and snippets.

@willsza
Last active February 8, 2024 14:08
Show Gist options
  • Save willsza/4dedcc8a286a342abe2706ef50facd16 to your computer and use it in GitHub Desktop.
Save willsza/4dedcc8a286a342abe2706ef50facd16 to your computer and use it in GitHub Desktop.
Validação de CPF
function validaCPF(cpf: string): boolean {
cpf = cpf.replace(/\D/g, '');
if (cpf.length !== 11 || /^(\d)\1+$/.test(cpf)) return false;
const calcularDigito = (base: number) => {
let soma = 0;
for (let i = 0; i < base - 1; i++) {
soma += parseInt(cpf.charAt(i)) * (base - i);
}
const resto = (soma * 10) % 11;
return resto >= 10 ? 0 : resto;
};
const digito1 = calcularDigito(10);
const digito2 = calcularDigito(11);
return cpf.charAt(9) === digito1.toString() && cpf.charAt(10) === digito2.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment