Skip to content

Instantly share code, notes, and snippets.

@wesdeveloper
Created August 22, 2019 20:04
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 wesdeveloper/a656a7f60819f34c6beedd02130b2f9e to your computer and use it in GitHub Desktop.
Save wesdeveloper/a656a7f60819f34c6beedd02130b2f9e to your computer and use it in GitHub Desktop.
Validate if a CNPJ is valid
/**
* Validate if a CNPJ is valid.
* @param {*} data - CNPJ
* @param {*} cnpjBlackList - Array with blacklist of wrongs CNPJs
* @returns {Boolean} return a boolean
*
* @example
* isCnpjValid('98.080.425/0011-00'); //false
*/
export const isCnpjValid = (
data = '',
cnpjBlackList = [
'00000000000000',
'11111111111111',
'22222222222222',
'33333333333333',
'44444444444444',
'55555555555555',
'66666666666666',
'77777777777777',
'88888888888888',
'99999999999999',
],
) => {
const cnpj = data.replace(/[^\d]+/g, '');
const isDigitValid = (digit = 1, cnpj) => {
const tamanho = digit === 1 ? 12 : 13;
let pos = tamanho - 7;
let numbers = cnpj.substring(0, tamanho);
let digits = cnpj.substring(tamanho);
let sum = 0;
for (let i = tamanho; i >= 1; i--) {
sum += numbers.charAt(tamanho - i) * pos--;
if (pos < 2) pos = 9;
}
const result = sum % 11 < 2 ? 0 : 11 - (sum % 11);
if (result !== parseInt(digits.charAt(0))) return false;
return true;
};
if (cnpj === '' || cnpj.length !== 14 || cnpjBlackList.find(current => cnpj === current))
return false;
return isDigitValid(1, cnpj) && isDigitValid(2, cnpj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment