Last active
June 6, 2025 19:44
-
-
Save joaohcrangel/8bd48bcc40b9db63bef7201143303937 to your computer and use it in GitHub Desktop.
Função para validar CPF em TypeScript
This file contains hidden or 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 isValidCPF(value: string) { | |
if (typeof value !== 'string') { | |
return false; | |
} | |
value = value.replace(/[^\d]+/g, ''); | |
if (value.length !== 11 || !!value.match(/(\d)\1{10}/)) { | |
return false; | |
} | |
const values = value.split('').map(el => +el); | |
const rest = (count) => (values.slice(0, count-12).reduce( (soma, el, index) => (soma + el * (count-index)), 0 )*10) % 11 % 10; | |
return rest(10) === values[9] && rest(11) === values[10]; | |
} |
Há uma falha nessa função. Ela aceita os CPFs 11111111111, 22222222222, ..., 99999999999 como válidos.
Sugestão:
function isValidCPF(cpf) { if (typeof cpf !== "string") return false cpf = cpf.replace(/[\s.-]*/igm, '') if ( !cpf || cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999" ) { return false } var soma = 0 var resto for (var i = 1; i <= 9; i++) soma = soma + parseInt(cpf.substring(i-1, i)) * (11 - i) resto = (soma * 10) % 11 if ((resto == 10) || (resto == 11)) resto = 0 if (resto != parseInt(cpf.substring(9, 10)) ) return false soma = 0 for (var i = 1; i <= 10; i++) soma = soma + parseInt(cpf.substring(i-1, i)) * (12 - i) resto = (soma * 10) % 11 if ((resto == 10) || (resto == 11)) resto = 0 if (resto != parseInt(cpf.substring(10, 11) ) ) return false return true }
if (/^(\d)\1+$/.test(CPF)) {
return false;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Precisei dessa função novamente em outro projeto. Só que nele eu tbm precisava da função que gerava o dígito verificador em outros lugares do código. Lá eu transformei ela num método funcional puro e extraí para o mesmo módulo. Apliquei a mesma mudança aqui mas mantive dentro da função para não poluir o escopo.