Last active
November 24, 2023 14:03
-
-
Save sethwololo/55e3261adc7f5d1bbb34abdfc0edc8ad to your computer and use it in GitHub Desktop.
Validador de CPF com TypeScript.
This file contains 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(/[^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