Created
December 8, 2023 18:42
-
-
Save eemr3/92b887be779a8c6045417095ae0111a8 to your computer and use it in GitHub Desktop.
Validar CNPJ (TS)
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
export function ValidaCNPJ(cnpj: string): boolean { | |
const b: number[] = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; | |
const c: string = cnpj.replace(/[^\d]/g, ''); | |
if (c.length !== 14) { | |
return false; | |
} | |
if (/0{14}/.test(c)) { | |
return false; | |
} | |
let n: number = 0; | |
for (let i = 0; i < 12; n += Number(c[i]) * Number(b[++i])); | |
if (c[12] !== ((n %= 11) < 2 ? '0' : (11 - n).toString())) { | |
return false; | |
} | |
n = 0; | |
for (let i = 0; i <= 12; n += Number(c[i]) * Number(b[i++])); | |
if (c[13] !== ((n %= 11) < 2 ? '0' : (11 - n).toString())) { | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment