Skip to content

Instantly share code, notes, and snippets.

@ssbreno
Created January 5, 2024 03:52
Show Gist options
  • Save ssbreno/5cc3200def876dbe4d114df6801e2818 to your computer and use it in GitHub Desktop.
Save ssbreno/5cc3200def876dbe4d114df6801e2818 to your computer and use it in GitHub Desktop.
validate-cnpj.ts
export const regexCNPJ = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;
export const validCNPJ = (value: string | number | number[] = '') => {
if (!value) return false;
const isString = typeof value === 'string';
if (isString && !regexCNPJ.test(value)) return false;
const numbers = matchNumbers(value);
if (numbers.length !== 14) return false;
const items = [...new Set(numbers)];
if (items.length === 1) return false;
const digit0 = validCalc(12, numbers);
const digit1 = validCalc(13, numbers);
return digit0 === numbers[12] && digit1 === numbers[13];
};
function validCalc(x: number, numbers: number[]) {
let factor = x - 7;
let sum = 0;
for (let i = 0; i < x; i++) {
sum += numbers[i] * factor--;
if (factor < 2) factor = 9;
}
const result = 11 - (sum % 11);
return result > 9 ? 0 : result;
}
function matchNumbers(value: string | number | number[] = '') {
const match = value
.toString()
.replace(/[^\d]+/g, '')
.match(/\d/g);
return Array.isArray(match) ? match.map(Number) : [];
}
@ssbreno
Copy link
Author

ssbreno commented Jan 5, 2024

validate-cnpj.spec.ts

import { validCNPJ } from './validate-cnpj';

describe('validCNPJ', () => {
  it('should validate a valid CNPJ', () => {
    expect(validCNPJ('04.470.781/0001-39')).toBeTruthy();
  });

  it('should invalidate an invalid CNPJ', () => {
    expect(validCNPJ('11.111.111/1111-11')).toBeFalsy();
  });

  it('should return false for an invalid CNPJ', () => {
    const cnpj = '34.574.376/0001-93';
    expect(validCNPJ(cnpj)).toBeFalsy();
  });

  it('should return false for a CNPJ with all identical digits', () => {
    const cnpj = '11.111.111/1111-11';
    expect(validCNPJ(cnpj)).toBeFalsy();
  });

  it('should return false for a CNPJ with incorrect length', () => {
    const cnpj = '34.574.376/0001';
    expect(validCNPJ(cnpj)).toBeFalsy();
  });

  it('should return false for a CNPJ with non-numeric characters', () => {
    const cnpj = '34a574b376/0001c92';
    expect(validCNPJ(cnpj)).toBeFalsy();
  });

  it('should return false for an empty string', () => {
    const cnpj = '';
    expect(validCNPJ(cnpj)).toBeFalsy();
  });

  it('should return false for a null value', () => {
    const cnpj = null;
    expect(validCNPJ(cnpj)).toBeFalsy();
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment