Created
March 18, 2024 13:17
-
-
Save sethwololo/19fc20a4863b2116131369dfdf4da99b to your computer and use it in GitHub Desktop.
Validador de CNPJ escrito em 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 cnpjPattern = /^(\d{2}[-.\s]?\d{3}[-.\s]?\d{3}[-.\s/]?\d{4}[-.\s]?\d{2})$/ | |
function calcDigit(cnpjArray: number[]) { | |
const x = cnpjArray.length | |
const { sum } = cnpjArray.reduce( | |
(acc, curr) => ({ | |
sum: acc.sum + curr * acc.factor, | |
factor: acc.factor > 2 ? acc.factor - 1 : 9, | |
}), | |
{ sum: 0, factor: x - 7 }, | |
) | |
const result = 11 - (sum % 11) | |
return result > 9 ? 0 : result | |
} | |
const isSameDigit = (numbers: number[]) => [...new Set(numbers)].length === 1 | |
export function validateCNPJ(cnpj: string) { | |
if (!cnpjPattern.test(cnpj)) return false | |
const cnpjArray = cnpj | |
.replace(/[^\d]+/g, '') | |
.split('') | |
.map(Number) | |
if (isSameDigit(cnpjArray)) return false | |
const checkDigits = cnpjArray.slice(12) | |
const firstDigit = calcDigit(cnpjArray.slice(0, 12)) | |
if (firstDigit !== checkDigits[0]) return false | |
const secondDigit = calcDigit(cnpjArray.slice(0, 13)) | |
if (secondDigit !== checkDigits[1]) return false | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment