All files / helpers/validators cnpj.js

100% Statements 25/25
100% Branches 12/12
100% Functions 4/4
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 599x 18x 8x 8x   100x   8x 100x 100x 100x 100x     8x 8x     18x   18x     17x 1x       16x 2x       14x                           10x     4x 4x 4x   4x        
const validateCNPJ = (cnpj) => {
  const verifierDigit = (numbers) => {
    let index = 2;
    const reverse = numbers
      .split('')
      .reduce((buffer, number) => [parseInt(number, 10)].concat(buffer), []);
 
    const sum = reverse.reduce((buffer, number) => {
      let aux = buffer;
      aux += number * index;
      index = index === 9 ? 2 : index + 1;
      return aux;
    }, 0);
 
    const mod = sum % 11;
    return mod < 2 ? 0 : 11 - mod;
  };
 
  const stripped = cnpj.replace(/[^\d]+/g, '');
 
  if (stripped === '') return false;
 
  // CNPJ must be defined
  if (!stripped) {
    return false;
  }
 
  // CNPJ must have 14 chars
  if (stripped.length !== 14) {
    return false;
  }
 
  // CNPJ can't be blacklisted
  if (
    [
      '00000000000000',
      '11111111111111',
      '22222222222222',
      '33333333333333',
      '44444444444444',
      '55555555555555',
      '66666666666666',
      '77777777777777',
      '88888888888888',
      '99999999999999',
    ].indexOf(stripped) >= 0
  ) {
    return false;
  }
 
  let numbers = stripped.substr(0, 12);
  numbers += verifierDigit(numbers);
  numbers += verifierDigit(numbers);
 
  return numbers.substr(-2) === stripped.substr(-2);
};
 
export default validateCNPJ;