Skip to content

Instantly share code, notes, and snippets.

@VictorQueiroz
Created May 10, 2025 22:20
Show Gist options
  • Select an option

  • Save VictorQueiroz/46699f882d13f0639a371e824e6f38b9 to your computer and use it in GitHub Desktop.

Select an option

Save VictorQueiroz/46699f882d13f0639a371e824e6f38b9 to your computer and use it in GitHub Desktop.
TypeScript function to check if a Brazilian CPF is valid or not.
isValidCPF('0') // false
function isValidCPF(cpf: string): boolean {
cpf = cpf.replace(/[^\d]+/g, '');
if (!cpf || cpf.length !== 11 || /^(\d)\1+$/.test(cpf)) return false;
const calcCheckDigit = (base: number[]) => {
const sum = base.reduce((acc, digit, idx) => acc + digit * (base.length + 1 - idx), 0);
const result = (sum * 10) % 11;
return result === 10 ? 0 : result;
};
const digits = cpf.split('').map(Number);
const firstNine = digits.slice(0, 9);
const check1 = calcCheckDigit(firstNine);
const check2 = calcCheckDigit([...firstNine, check1]);
return check1 === digits[9] && check2 === digits[10];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment