Last active
February 8, 2024 14:08
-
-
Save willsza/4dedcc8a286a342abe2706ef50facd16 to your computer and use it in GitHub Desktop.
Validação de CPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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