Skip to content

Instantly share code, notes, and snippets.

@felipekm
Created November 24, 2015 18:47
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 felipekm/a2c68c328eb218e127b6 to your computer and use it in GitHub Desktop.
Save felipekm/a2c68c328eb218e127b6 to your computer and use it in GitHub Desktop.
Valida CNPJ
function validarCNPJ(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, '');
if (cnpj === '') {
return false;
}
if (cnpj.length !== 14) {
return false;
}
tamanho = cnpj.length - 2;
numeros = cnpj.substring(0, tamanho);
digitos = cnpj.substring(tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2) {
pos = 9;
}
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos.charAt(0)) {
return false;
}
tamanho = tamanho + 1;
numeros = cnpj.substring(0, tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2) {
pos = 9;
}
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos.charAt(1)) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment