Skip to content

Instantly share code, notes, and snippets.

@eemr3
Created December 8, 2023 18:42
Show Gist options
  • Save eemr3/92b887be779a8c6045417095ae0111a8 to your computer and use it in GitHub Desktop.
Save eemr3/92b887be779a8c6045417095ae0111a8 to your computer and use it in GitHub Desktop.
Validar CNPJ (TS)
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