Skip to content

Instantly share code, notes, and snippets.

@danilosilvadev
Last active September 3, 2019 14:58
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 danilosilvadev/63352d23089edb65edfcaaa188d10c43 to your computer and use it in GitHub Desktop.
Save danilosilvadev/63352d23089edb65edfcaaa188d10c43 to your computer and use it in GitHub Desktop.
const cnpj = (value) => {
console.log(value, 'o valor q entrou')
var cnpj = value.replace(/[^\d]+/g,'');
// cnpjs inválidos conhecidos
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for(i of numbers) {
if (i.repeat(14) === cnpj) { return false}
}
// checa os dois dígitos verificadores, verificando sua validade de acordo com o algoritmo do CNPJ
let tamanho = cnpj.length - 2, numeros = cnpj.substring(0,tamanho), digitos = cnpj.substring(tamanho), soma = 0, pos = tamanho - 7;
for (var i = tamanho; i >= 1; i--) {
soma += numeros[tamanho - i] * pos--;
console.log('tamanho', soma, numeros[tamanho - i], pos)
if (pos < 2)
pos = 9;
}
var resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos[0])
return false;
tamanho = tamanho + 1;
numeros = cnpj.substring(0,tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros[tamanho - i] * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
// testa os casos
switch(true) {
case (resultado != digitos[1]):
return false;
case (cnpj == '' || cnpj == undefined || cnpj == null):
return false;
case (cnpj.length != 14):
return false
default:
return true;
}
}
const valid = {
cnpj
}
export default valid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment