Skip to content

Instantly share code, notes, and snippets.

@migtibincoski
Created August 9, 2024 01:08
Show Gist options
  • Save migtibincoski/683a2414db5c874a8a1e034bd2ac4603 to your computer and use it in GitHub Desktop.
Save migtibincoski/683a2414db5c874a8a1e034bd2ac4603 to your computer and use it in GitHub Desktop.
Validação de CPF com JavaScript
function validarCPF(cpf) {
cpf = cpf.replace(/[^\d]+/g, '');
if (cpf.length !== 11 || /^(\d)\1+$/.test(cpf)) {
return false;
}
let soma = 0;
let resto;
for (let i = 1; i <= 9; i++) {
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 (let i = 1; i <= 10; i++) {
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;
}
console.log(validarCPF("123.456.789.09")); // Retorna true ou false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment