Created
February 20, 2017 15:07
-
-
Save garrefa/e747d03624034bf24944d072891e55e2 to your computer and use it in GitHub Desktop.
Revisions
-
garrefa created this gist
Feb 20, 2017 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,38 @@ 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; }