Last active
April 9, 2025 14:48
-
-
Save sethwololo/55e3261adc7f5d1bbb34abdfc0edc8ad to your computer and use it in GitHub Desktop.
Validador de CPF com 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
const cpfPattern = /^(\d{11}|\d{3}\.\d{3}\.\d{3}-\d{2})$/ | |
export function validateCPF(value: string): boolean { | |
if (!value.match(cpfPattern)) return false | |
// Remove caracteres especiais e espaços | |
const unformattedCpf = value.replace(/[^\d]/g, '') | |
if (unformattedCpf.length !== 11) return false; | |
const allDigitsEqual = /^(\d)\1{10}$/.test(unformattedCpf) | |
if (allDigitsEqual) return false; | |
// Separa os dígitos verificadores do parâmetro | |
const checkDigits = unformattedCpf | |
.slice(9, 11) | |
.split('') | |
.map(item => Number(item)) | |
// Primeiro dígito verificador | |
// Estima o primeiro | |
const firstDigitSum = unformattedCpf | |
.slice(0, 9) | |
.split('') | |
.reduce( | |
(accumulator, currentNumber, index) => accumulator + Number(currentNumber) * (10 - index), | |
0, | |
) | |
const firstDigitRest = firstDigitSum % 11 | |
const firstDigit = firstDigitRest < 2 ? 0 : 11 - firstDigitRest | |
if (checkDigits[0] !== firstDigit) return false | |
// Segundo dígito verificador | |
const secondDigitSum = unformattedCpf | |
.slice(0, 10) | |
.split('') | |
.reduce( | |
(accumulator, currentNumber, index) => accumulator + Number(currentNumber) * (11 - index), | |
0, | |
) | |
const secondDigitRest = secondDigitSum % 11 | |
const secondDigit = secondDigitRest < 2 ? 0 : 11 - secondDigitRest | |
if (checkDigits[1] !== secondDigit) return false | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment