h7-validate-cnpj
Version:
A TypeScript library to validate Brazilian CNPJ. It ensures valid structure, verifies check digits, and handles known invalid patterns.
65 lines (64 loc) • 2.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CNPJValidator = void 0;
/**
* @author
* @see https://github.com/herlandio
*
* Class to validate Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica).
*/
class CNPJValidator {
/**
* Constructor to initialize the CNPJ value.
* @param cnpj - The CNPJ string to validate.
*/
constructor(cnpj) {
this.cnpj = cnpj.replace(/[^\d]/g, ''); // Normalize input
}
/**
* Validates the CNPJ.
* @returns `true` if the CNPJ is valid; otherwise, `false`.
*/
isValid() {
if (!this.isValidLength() || this.isKnownInvalid())
return false;
const weights = [
[5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2],
[6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2],
];
let base = this.cnpj.slice(0, 12);
for (let i = 0; i < 2; i++) {
const checkDigit = this.calculateCheckDigit(base, weights[i]);
base += checkDigit;
}
return this.cnpj === base;
}
/**
* Checks if the CNPJ has the correct length of 14 digits.
* @returns `true` if the length is valid; otherwise, `false`.
*/
isValidLength() {
return this.cnpj.length === 14;
}
/**
* Checks if the CNPJ matches known invalid patterns, such as repeated sequences.
* @returns `true` if the CNPJ is invalid; otherwise, `false`.
*/
isKnownInvalid() {
return /^(\d)\1+$/.test(this.cnpj); // Matches repeated sequences like "11111111111111"
}
/**
* Calculates a single check digit for a CNPJ based on the provided weights.
* @param base - The numeric base string to validate against.
* @param weights - The weights used in the calculation.
* @returns The calculated check digit as a string.
*/
calculateCheckDigit(base, weights) {
const sum = base
.split('')
.reduce((acc, digit, index) => acc + parseInt(digit) * weights[index], 0);
const remainder = sum % 11;
return (remainder < 2 ? 0 : 11 - remainder).toString();
}
}
exports.CNPJValidator = CNPJValidator;