Skip to content

Instantly share code, notes, and snippets.

@garrefa
Created February 20, 2017 15:07
Show Gist options
  • Select an option

  • Save garrefa/e747d03624034bf24944d072891e55e2 to your computer and use it in GitHub Desktop.

Select an option

Save garrefa/e747d03624034bf24944d072891e55e2 to your computer and use it in GitHub Desktop.
function validateCNPJ(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g,'');
if (cnpj.length != 14) return false;
// Remove known invalid CNPJs
if (cnpj === "00000000000000" ||
cnpj === "11111111111111" ||
cnpj === "22222222222222" ||
cnpj === "33333333333333" ||
cnpj === "44444444444444" ||
cnpj === "55555555555555" ||
cnpj === "66666666666666" ||
cnpj === "77777777777777" ||
cnpj === "88888888888888" ||
cnpj === "99999999999999") return false;
// Validate Blocks
const blocksDivision = cnpj.length - 2
const headBlock = cnpj.substring(0,blocksDivision);
const tailBlock = cnpj.substring(blocksDivision);
let sum = 0;
let pos = blocksDivision - 7;
for (i = blocksDivision; i >= 1; i--) {
sum += headBlock.charAt(blocksDivision - i) * pos--;
if (pos < 2) pos = 9;
}
let validationCheck = sum % 11 < 2 ? 0 : 11 - sum % 11;
if (validationCheck != tailBlock.charAt(0)) return false;
blocksDivision = blocksDivision + 1;
headBlock = cnpj.substring(0,blocksDivision);
sum = 0;
pos = blocksDivision - 7;
for (i = blocksDivision; i >= 1; i--) {
sum += headBlock.charAt(blocksDivision - i) * pos--;
if (pos < 2) pos = 9;
}
validationCheck = sum % 11 < 2 ? 0 : 11 - sum % 11;
if (validationCheck != tailBlock.charAt(1)) return false;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment