@studiovisual/brazilian-validator-js
Version:
A lightweight and efficient JavaScript library for validating Brazilian documents and phone numbers
78 lines (77 loc) • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidCNPJLength = isValidCNPJLength;
exports.isValidCNPJDigits = isValidCNPJDigits;
exports.isValidCNPJFirstCheckDigit = isValidCNPJFirstCheckDigit;
exports.isValidCNPJSecondCheckDigit = isValidCNPJSecondCheckDigit;
exports.isValidCNPJ = isValidCNPJ;
const utils_1 = require("./utils");
/**
* Checks if the provided CNPJ has a valid length.
* @param value The CNPJ value to validate.
* @returns A boolean indicating whether the length is valid.
*/
function isValidCNPJLength(value) {
value = (0, utils_1.extractDigits)(value);
// Checks if the CNPJ number has 14 digits
return value.length === 14;
}
/**
* Checks if the provided CNPJ has a valid length.
* @param value The CNPJ value to validate.
* @returns A boolean indicating whether the length is valid.
*/
function isValidCNPJDigits(value) {
value = (0, utils_1.extractDigits)(value);
// Eliminates invalids with all the same digits
const isAllEqual = /^(\d)\1+$/.test(value);
return !isAllEqual;
}
/**
* Checks if the provided CNPJ has a valid firs check digit.
* @param value The CNPJ value to validate.
* @returns A boolean indicating whether the firs check digit is valid.
*/
function isValidCNPJFirstCheckDigit(value) {
value = (0, utils_1.extractDigits)(value);
let sum = 0;
let factor = 5;
for (let i = 0; i < 12; i++) {
sum += parseInt(value.charAt(i), 10) * factor--;
if (factor === 1)
factor = 9;
}
const remainder = sum % 11;
const digit = remainder < 2 ? 0 : 11 - remainder;
return parseInt(value.charAt(12), 10) === digit;
}
/**
* Checks if the provided CNPJ has a valid second check digit.
* @param value The CNPJ value to validate.
* @returns A boolean indicating whether the second check digit is valid.
*/
function isValidCNPJSecondCheckDigit(value) {
value = (0, utils_1.extractDigits)(value);
let sum = 0;
let factor = 6;
for (let i = 0; i < 13; i++) {
sum += parseInt(value.charAt(i), 10) * factor--;
if (factor === 1)
factor = 9;
}
const remainder = sum % 11;
const digit = remainder < 2 ? 0 : 11 - remainder;
return parseInt(value.charAt(13), 10) === digit;
}
/**
* Checks if the provided CNPJ is valid.
* @param value The CNPJ value to validate.
* @returns A boolean indicating whether the CNPJ is valid.
*/
function isValidCNPJ(value) {
// Check if the CNPJ number satisfies all the conditions: length, not equals digits, first check digit and second check digit
return (isValidCNPJLength(value) &&
isValidCNPJDigits(value) &&
isValidCNPJFirstCheckDigit(value) &&
isValidCNPJSecondCheckDigit(value));
}