Skip to content

Instantly share code, notes, and snippets.

@danilobatistaqueiroz
Forked from alexbruno/valid.cnpj.ts
Created June 13, 2019 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilobatistaqueiroz/72380e8fe6f13b946586f0a480540349 to your computer and use it in GitHub Desktop.
Save danilobatistaqueiroz/72380e8fe6f13b946586f0a480540349 to your computer and use it in GitHub Desktop.
function cnpj(s) {
let cnpj = s.replace(/[^\d]+/g, '')
// Valida a quantidade de caracteres
if (cnpj.length !== 14)
return false
// Elimina inválidos com todos os caracteres iguais
if (/^(\d)\1+$/.test(cnpj))
return false
// Cáculo de validação
let t = cnpj.length - 2,
d = cnpj.substring(t),
d1 = parseInt(d.charAt(0)),
d2 = parseInt(d.charAt(1)),
calc = x => {
let n = cnpj.substring(0, x),
y = x - 7,
s = 0,
r = 0
for (let i = x; i >= 1; i--) {
s += n.charAt(x - i) * y--;
if (y < 2)
y = 9
}
r = 11 - s % 11
return r > 9 ? 0 : r
}
return calc(t) === d1 && calc(t + 1) === d2
}
@alexbruno
Copy link

Atualizei o script para um código mais moderno e aderente às boas práticas JS atuais.
Fique à vontade para atualizar o seu também.
Aproveitei e fiz um de CPF que também é muito útil.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment