Skip to content

Instantly share code, notes, and snippets.

@miroswd
Last active February 3, 2023 13:50
Show Gist options
  • Save miroswd/0e5cb1985c8b38dc53ad69f44df2c75d to your computer and use it in GitHub Desktop.
Save miroswd/0e5cb1985c8b38dc53ad69f44df2c75d to your computer and use it in GitHub Desktop.
CPF validator using typescript | validate CPF using typescript
const validateCPF = (cpf: string): boolean => {
if (!cpf) return false;
const onlyNumbersCPF = cpf.replace(/[^\d]+/g, "");
const invalidCPFs = Array.from("0123456789").map((i) => i.repeat(11));
if (onlyNumbersCPF.length !== 11 || invalidCPFs.includes(onlyNumbersCPF)) {
return false;
}
let sum = 0;
let rest;
for (let i = 1; i <= 9; i++) {
sum += parseInt(onlyNumbersCPF.substring(i - 1, i)) * (11 - i);
}
rest = (sum * 10) % 11;
if (rest === 10 || rest === 11) {
rest = 0;
}
if (rest !== parseInt(onlyNumbersCPF.substring(9, 10))) {
return false;
}
sum = 0;
for (let i = 1; i <= 10; i++) {
sum += parseInt(onlyNumbersCPF.substring(i - 1, i)) * (12 - i);
}
rest = (sum * 10) % 11;
if (rest === 10 || rest === 11) {
rest = 0;
}
if (rest !== parseInt(onlyNumbersCPF.substring(10, 11))) {
return false;
}
return true;
};
export { validateCPF };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment