Skip to content

Instantly share code, notes, and snippets.

@sethwololo
Last active November 24, 2023 14:03
Show Gist options
  • Save sethwololo/55e3261adc7f5d1bbb34abdfc0edc8ad to your computer and use it in GitHub Desktop.
Save sethwololo/55e3261adc7f5d1bbb34abdfc0edc8ad to your computer and use it in GitHub Desktop.
Validador de CPF com TypeScript.
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(/[^A-z\d][\\^\s]?/g, '')
// 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 ? 11 - firstDigitRest : 0
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 ? 11 - secondDigitRest : 0
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