Created
May 10, 2025 22:20
-
-
Save VictorQueiroz/46699f882d13f0639a371e824e6f38b9 to your computer and use it in GitHub Desktop.
TypeScript function to check if a Brazilian CPF is valid or not.
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
| isValidCPF('0') // false |
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(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