Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

validation-br

Package Overview
Dependencies
Maintainers
0
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

validation-br - npm Package Compare versions

Comparing version 1.4.5 to 1.5.1

dist/utils-checkRepeatedSequence.test.d.ts

2

.prettierrc.js
module.exports = {
semi: false,
semi: true,
trailingComma: 'all',

@@ -4,0 +4,0 @@ singleQuote: true,

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -52,3 +52,7 @@ /**

*/
export declare const dv: (value: string | number) => string;
type FakeInput = {
withMask?: boolean;
alphanumeric?: boolean;
};
export declare function dv(value: string | number): string;
/**

@@ -60,3 +64,3 @@ * Aplica uma máscara ao número informado

*/
export declare const mask: (value: string | number) => string;
export declare function mask(value: string | number): string;
/**

@@ -66,3 +70,4 @@ *

*/
export declare const fake: (withMask?: boolean) => string;
export declare function fake(options?: FakeInput): string;
export declare function fake(withMask?: boolean): string;
/**

@@ -76,3 +81,3 @@ * validateOrFail()

*/
export declare const validateOrFail: (value: string | number) => boolean;
export declare function validateOrFail(value: string | number): boolean;
/**

@@ -85,3 +90,3 @@ * validate()

*/
export declare const validate: (value: string | number) => boolean;
export declare function validate(value: string | number): boolean;
export default validate;

@@ -57,6 +57,10 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = exports.validateOrFail = exports.fake = exports.mask = exports.dv = void 0;
exports.dv = dv;
exports.mask = mask;
exports.fake = fake;
exports.validateOrFail = validateOrFail;
exports.validate = validate;
const ValidationBRError_1 = __importDefault(require("./data/ValidationBRError"));
const utils_1 = require("./utils");
const dv = (value) => {
function dv(value) {
const cnpj = (0, utils_1.clearValue)(value, 12, {

@@ -66,9 +70,8 @@ trimAtRight: true,

});
const sum1 = (0, utils_1.sumElementsByMultipliers)(cnpj.substring(0, 12), '543298765432');
const dv1 = (0, utils_1.sumToDV)(sum1);
const sum2 = (0, utils_1.sumElementsByMultipliers)(cnpj.substring(0, 12) + dv1, '6543298765432');
const dv2 = (0, utils_1.sumToDV)(sum2);
const dv1Factors = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
const dv1 = sumToDvWithAlpha(cnpj.substring(0, 12), dv1Factors);
const dv2Factors = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
const dv2 = sumToDvWithAlpha(cnpj.substring(0, 12) + dv1, dv2Factors);
return `${dv1}${dv2}`;
};
exports.dv = dv;
}
/**

@@ -80,16 +83,13 @@ * Aplica uma máscara ao número informado

*/
const mask = (value) => (0, utils_1.applyMask)(value, '00.000.000/0000-00');
exports.mask = mask;
/**
*
*
*/
const fake = (withMask = false) => {
function mask(value) {
return (0, utils_1.applyMask)(value, '00.000.000/0000-00');
}
function fake(options = false) {
const num = (0, utils_1.fakeNumber)(12, true);
const cnpj = `${num}${(0, exports.dv)(num)}`;
const cnpj = `${num}${dv(num)}`;
const withMask = typeof options === 'boolean' ? options : options.withMask;
if (withMask)
return (0, exports.mask)(cnpj);
return mask(cnpj);
return cnpj;
};
exports.fake = fake;
}
/**

@@ -103,5 +103,5 @@ * validateOrFail()

*/
const validateOrFail = (value) => {
function validateOrFail(value) {
const cnpj = (0, utils_1.clearValue)(value, 14, {
fillZerosAtLeft: true,
fillZerosAtLeft: false,
rejectEmpty: true,

@@ -111,8 +111,7 @@ rejectHigherLength: true,

});
if ((0, exports.dv)(cnpj) !== cnpj.substring(12, 14)) {
if (dv(cnpj) !== cnpj.substring(12, 14)) {
throw ValidationBRError_1.default.INVALID_DV;
}
return true;
};
exports.validateOrFail = validateOrFail;
}
/**

@@ -125,5 +124,5 @@ * validate()

*/
const validate = (value) => {
function validate(value) {
try {
return (0, exports.validateOrFail)(value);
return validateOrFail(value);
}

@@ -133,5 +132,27 @@ catch (error) {

}
};
exports.validate = validate;
exports.default = exports.validate;
}
exports.default = validate;
/**
*
* Converte o número para
*
*
*/
function asciiTableConverter(character) {
if (/^\d$/.test(character))
return +character;
const ascii = character.toLocaleUpperCase().charCodeAt(0) - 48;
return ascii;
}
/**
*
*
*
*/
function sumToDvWithAlpha(value, multiplier) {
const sum = [...value]
.map(character => asciiTableConverter(character))
.reduce((sum, asciiChar, index) => sum + asciiChar * multiplier[index], 0);
return (0, utils_1.sumToDV)(sum);
}
//# sourceMappingURL=cnpj.js.map

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -5,3 +5,3 @@ export default class ValidationBRError extends Error {

static MAX_LEN_EXCEDEED: ValidationBRError;
static SEQUENCE_REPEATED: ValidationBRError;
static REPEATED_SEQUENCE: ValidationBRError;
}

@@ -5,7 +5,7 @@ "use strict";

}
exports.default = ValidationBRError;
ValidationBRError.INVALID_DV = new ValidationBRError('Dígito verificador inválido');
ValidationBRError.EMPTY_VALUE = new ValidationBRError('Valor não preenchido');
ValidationBRError.MAX_LEN_EXCEDEED = new ValidationBRError('Número de caracteres excedido');
ValidationBRError.SEQUENCE_REPEATED = new ValidationBRError('Sequência de números repetidos não permitida');
ValidationBRError.REPEATED_SEQUENCE = new ValidationBRError('Sequência de números repetidos não permitida');
exports.default = ValidationBRError;
//# sourceMappingURL=ValidationBRError.js.map

@@ -0,0 +0,0 @@ export declare const isCNH: (value: string | number) => boolean;

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ /**

@@ -85,3 +85,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports._getSubCourt = exports.validate = exports.validateOrFail = exports.fake = exports.mask = exports.dv = void 0;
exports.validate = exports.validateOrFail = exports.fake = exports.mask = exports.dv = void 0;
exports._getSubCourt = _getSubCourt;
const ValidationBRError_1 = __importDefault(require("./data/ValidationBRError"));

@@ -189,4 +190,3 @@ const utils_1 = require("./utils");

}
exports._getSubCourt = _getSubCourt;
exports.default = exports.validate;
//# sourceMappingURL=judicialProcess.js.map

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ "use strict";

@@ -1,1 +0,1 @@

declare const applyMask: any;
export {};

@@ -1,1 +0,1 @@

declare const fakeNumber: any;
export {};
declare const invalidListGenerator: any;
declare const randomLetter: any;

@@ -1,1 +0,1 @@

declare const sumElementsByMultipliers: any;
export {};

@@ -1,1 +0,1 @@

declare const sumToDV: any;
export {};

@@ -11,14 +11,12 @@ /**

/**
* Cria uma lista de valores repetidos no tamanho do documento para eliminar
* valores que já conhecemos como inválidos
* Checa se o número repassado possui todos os digitos iguais
*
* @example
* invalidListGenerator(10, 11)
* //-> [00000000000, 11111111111, ....., 99999999999]
* checkRepeatedSequence(12345678)
* // -> false
* checkRepeatedSequence(11111111)
* // -> true
*
* @param {Integer} length Número de itens do array
* @param {Integer} size Tamanho da string gerada
* @returns {Array} Lista de valores
*/
export declare function invalidListGenerator(size: number): string[];
export declare function checkRepeatedSequence(value: string): boolean;
/**

@@ -25,0 +23,0 @@ * Multiplica os elementos de uma string com os elementos de outra, ou de um array

@@ -6,3 +6,11 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.randomLetter = exports.applyMask = exports.removeFromPosition = exports.insertAtPosition = exports.clearValue = exports.fakeNumber = exports.sumElementsByMultipliers = exports.invalidListGenerator = exports.sumToDV = void 0;
exports.sumToDV = sumToDV;
exports.checkRepeatedSequence = checkRepeatedSequence;
exports.sumElementsByMultipliers = sumElementsByMultipliers;
exports.fakeNumber = fakeNumber;
exports.clearValue = clearValue;
exports.insertAtPosition = insertAtPosition;
exports.removeFromPosition = removeFromPosition;
exports.applyMask = applyMask;
exports.randomLetter = randomLetter;
const ValidationBRError_1 = __importDefault(require("./data/ValidationBRError"));

@@ -20,19 +28,15 @@ /**

}
exports.sumToDV = sumToDV;
/**
* Cria uma lista de valores repetidos no tamanho do documento para eliminar
* valores que já conhecemos como inválidos
* Checa se o número repassado possui todos os digitos iguais
*
* @example
* invalidListGenerator(10, 11)
* //-> [00000000000, 11111111111, ....., 99999999999]
* checkRepeatedSequence(12345678)
* // -> false
* checkRepeatedSequence(11111111)
* // -> true
*
* @param {Integer} length Número de itens do array
* @param {Integer} size Tamanho da string gerada
* @returns {Array} Lista de valores
*/
function invalidListGenerator(size) {
return [...Array(10).keys()].map((f) => String(f).repeat(size));
function checkRepeatedSequence(value) {
return [...value].every(digit => digit === value[0]);
}
exports.invalidListGenerator = invalidListGenerator;
/**

@@ -51,7 +55,7 @@ * Multiplica os elementos de uma string com os elementos de outra, ou de um array

function sumElementsByMultipliers(value, multiplier) {
if (typeof multiplier === 'string')
multiplier = multiplier.split('').map((n) => Number(n));
return multiplier.reduce((accu, curr, i) => accu + curr * Number(value.charAt(i)), 0);
if (!Array.isArray(multiplier)) {
multiplier = [...multiplier].map((n) => Number(n));
}
return multiplier.reduce((accu, curr, i) => accu + curr * Number(value[i]), 0);
}
exports.sumElementsByMultipliers = sumElementsByMultipliers;
/**

@@ -75,3 +79,2 @@ * fakeNumber()

}
exports.fakeNumber = fakeNumber;
/**

@@ -98,15 +101,15 @@ * Limpa um número informado, retirando caracteres diferentes de números,

if (options) {
if (options.rejectEmpty === true && clearedValue.length === 0) {
const shouldRejectEmpty = options.rejectEmpty === true && clearedValue.length === 0;
if (shouldRejectEmpty) {
throw ValidationBRError_1.default.EMPTY_VALUE;
}
if (options.rejectHigherLength === true && length && clearedValue.length > length) {
const shouldRejectHigherLength = options.rejectHigherLength === true && length && clearedValue.length > length;
if (shouldRejectHigherLength) {
throw ValidationBRError_1.default.MAX_LEN_EXCEDEED;
}
if (options.rejectEqualSequence === true && length) {
const invalidList = invalidListGenerator(length);
if (invalidList.includes(clearedValue)) {
throw ValidationBRError_1.default.SEQUENCE_REPEATED;
}
const shouldRejectEqualSequence = options.rejectEqualSequence === true && length;
if (shouldRejectEqualSequence) {
if (checkRepeatedSequence(clearedValue))
throw ValidationBRError_1.default.REPEATED_SEQUENCE;
}
// if (!length || clearedValue.length === length) return clearedValue
if (length && options.fillZerosAtLeft)

@@ -119,3 +122,2 @@ clearedValue = clearedValue.padStart(length, '0');

}
exports.clearValue = clearValue;
/**

@@ -138,3 +140,2 @@ * insertAtPosition()

}
exports.insertAtPosition = insertAtPosition;
/**

@@ -157,3 +158,2 @@ * removeFromPosition()

}
exports.removeFromPosition = removeFromPosition;
/**

@@ -183,3 +183,2 @@ * applyMask()

}
exports.applyMask = applyMask;
/**

@@ -199,3 +198,2 @@ * randomLetter()

}
exports.randomLetter = randomLetter;
//# sourceMappingURL=utils.js.map
module.exports = {
globals: {
'ts-jest': {
tsconfig: 'tsconfig.json',
},
},
moduleFileExtensions: ['ts', 'js'],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
'^.+\\.(ts|tsx)$': ['ts-jest', { /* ts-jest config goes here in Jest */ }],
},

@@ -11,0 +6,0 @@ testRegex: '(/src/.*\\.(test|spec))\\.(jsx?|tsx?)$',

{
"name": "validation-br",
"description": "Brazilian personal documents validation - cpf, cnpj, titulo, pis/pasep, cnh, renavam, processos judiciais, protocolo federal, código de rastreamento dos correios",
"version": "1.4.5",
"version": "1.5.1",
"main": "dist/index.js",

@@ -14,12 +14,4 @@ "types": "./dist/index.d.ts",

"test:coverage": "jest --collectCoverageFrom=src/**/*.ts --coverage",
"lint:list": "eslint */**/*.js --fix",
"format": "prettier --write \"./**/*.{js,ts,json}\"",
"prepublish": "yarn build",
"prepare": "husky install"
"format": "prettier --write \"./**/*.{js,ts,json}\""
},
"husky": {
"hooks": {
"pre-commit": "tsc --noEmit && lint-staged"
}
},
"lint-staged": {

@@ -34,19 +26,6 @@ "*.{js,ts}": [

"@types/node": "^14.14.2",
"@typescript-eslint/eslint-plugin": "^4.0.0",
"@typescript-eslint/parser": "^3.10.1",
"eslint": "^7.11.0",
"eslint-config-airbnb-base": "^14.2.0",
"eslint-config-prettier": "^6.14.0",
"eslint-import-resolver-node": "^0.3.4",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-no-only-tests": "^2.4.0",
"eslint-plugin-prettier": "^3.1.4",
"husky": "^7.0.4",
"jest": "^27.4.7",
"lint-staged": "^10.4.2",
"prettier": "^2.1.2",
"ts-jest": "^27.1.2",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"ts-node": "^9.0.0",
"typescript": "^4.0.3"
"typescript": "^5.6.2"
},

@@ -53,0 +32,0 @@ "repository": {

# validation-br
Biblioteca de validação de documentos pessoais do Brasil com suporte a CPF, CNPJ, Título Eleitoral, PIS/PASEP, CNH. Também valida numerações de outros tipos de registros como RENAVAM, Processos Judiciais, Número de Protocolo do Governo Federal e Objetos registrados de Rastreamento dos Correios.
Biblioteca de validação de documentos pessoais do Brasil com suporte a CPF, CNPJ (numérico e alfanumérico), Título Eleitoral, PIS/PASEP, CNH. Também valida numerações de outros tipos de registros como RENAVAM, Processos Judiciais, Número de Protocolo do Governo Federal e Objetos registrados de Rastreamento dos Correios.

@@ -129,2 +129,4 @@ Validation-BR também permite criação de números fake para facilitar o desenvolvimento e testes, além de aplicar máscaras e calcular somente os dígitos verificadores.

> A partir da [Nota Técnica conjunta COCAD/SUARA/RFB nº 49 de 14 de maio de 2024](https://github.com/user-attachments/files/15851229/Nota.COCAD.SUARA.2024.05.49.CNPJ.Alfanumerico-1.pdf), os números de CNPJ poderão ser alfanuméricos. A alteração entra em uso em 2026.
```js

@@ -149,2 +151,5 @@ // Importação somente da validação

cnpj.fake(true) // -> 55.585.709/0001-98
cnpj.fake({ withMask: true}) // -> 55.585.709/0001-98
cnpj.fake({ withMask: true, alphanumeric: true}) // -> A1.222.333/0001-50
cnpj.fake({ withMask: false, alphanumeric: true}) // -> A1222333/0001-50

@@ -415,3 +420,3 @@ // Aplica uma máscara

Github actions executados nas versões 12, 14, 16, 18 e 20 do Node.
Github actions executados nas versões 18, 20 e 22 do Node.

@@ -423,2 +428,6 @@ ![Github actions executados nas versões 12, 14, 16, 18 e 20 do Node](https://github.com/klawdyo/validation-br/assets/100168/50f5b3c3-f1b0-46ac-a6b1-e31a366b27c7)

- **16/12/2023**:
- 1.5.0
- CNPJ alfanumérico
- Removidos github actions dos node 12, 14 e 16 e acrescentado o 22
- **16/12/2023**:
- 1.4.5

@@ -425,0 +434,0 @@ - Corrige o caminho da definição dos types. (Thanks @ishigami)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc