@thalys.mazzitelli.cotta/cnpj-validator-br 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,6 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thalys Mazzitelli Cotta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files...
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # 📦 CNPJ Validator BR
2
+
3
+ Validador de CNPJ para Node.js com suporte a:
4
+
5
+ * ✅ CNPJ tradicional (numérico)
6
+ * ✅ Novo CNPJ alfanumérico (Brasil - 2026)
7
+ * ✅ Máscara automática
8
+ * âś… Limpeza de entrada
9
+ * ✅ Validação com dígito verificador (módulo 11)
10
+
11
+ ---
12
+
13
+ ## 🚀 Instalação
14
+
15
+ > (Disponível após publicação no npm)
16
+
17
+ ```bash
18
+ npm install @thalys/cnpj-validator-br
19
+ ```
20
+
21
+ ---
22
+
23
+ ## 📌 Uso
24
+
25
+ ```js
26
+ const cnpj = require("@thalys/cnpj-validator-br");
27
+
28
+ // Limpar (remove caracteres especiais)
29
+ cnpj.clean("12.345.678/0001-95");
30
+ // "12345678000195"
31
+
32
+ // Formatar (aplica máscara)
33
+ cnpj.format("12345678000195");
34
+ // "12.345.678/0001-95"
35
+
36
+ // Validar (retorna true ou false)
37
+ cnpj.validate("12.345.678/0001-95");
38
+ // true
39
+ ```
40
+
41
+ ---
42
+
43
+ ## 🔢 Exemplo com CNPJ alfanumérico (2026)
44
+
45
+ ```js
46
+ cnpj.clean("12.ABC.345/01DE-35");
47
+ // "12ABC34501DE35"
48
+
49
+ cnpj.format("12ABC34501DE35");
50
+ // "12.ABC.345/01DE-35"
51
+
52
+ cnpj.validate("12.ABC.345/01DE-35");
53
+ // true ou false
54
+ ```
55
+
56
+ ---
57
+
58
+ ## đź§  Funcionalidades
59
+
60
+ * Limpeza de caracteres inválidos
61
+ * Formatação padrão: `XX.XXX.XXX/XXXX-XX`
62
+ * Validação com módulo 11
63
+ * Compatível com novo padrão alfanumérico (Brasil - 2026)
64
+ * Suporte a entrada parcial (ideal para inputs)
65
+
66
+ ---
67
+
68
+ ## 🏗️ Estrutura do Projeto
69
+
70
+ ```
71
+ cnpj-validator-br/
72
+ ├─ src/
73
+ │ ├─ clean.js
74
+ │ ├─ format.js
75
+ │ ├─ dv.js
76
+ │ ├─ validate.js
77
+ │ └─ index.js
78
+ ├─ tests/
79
+ │ └─ cnpj.test.js
80
+ ├─ package.json
81
+ ├─ README.md
82
+ ├─ .gitignore
83
+ └─ LICENSE
84
+ ```
85
+
86
+ ---
87
+
88
+ ## ⚙️ Como rodar localmente
89
+
90
+ ```bash
91
+ node src/index.js
92
+ ```
93
+
94
+ Ou usar no modo interativo:
95
+
96
+ ```bash
97
+ node
98
+ ```
99
+
100
+ ```js
101
+ const cnpj = require("./src");
102
+
103
+ cnpj.validate("12.345.678/0001-95");
104
+ ```
105
+
106
+ ---
107
+
108
+ ## đź§Ş Testes
109
+
110
+ Os testes estĂŁo localizados na pasta:
111
+
112
+ ```
113
+ tests/
114
+ ```
115
+
116
+ VocĂŞ pode executar manualmente via Node ou integrar futuramente com frameworks como:
117
+
118
+ * Jest
119
+ * Mocha
120
+
121
+ ---
122
+
123
+ ## 📚 Sobre o cálculo do DV
124
+
125
+ A validação do CNPJ é feita com base no algoritmo de **módulo 11**, utilizando:
126
+
127
+ * pesos específicos para cada posição
128
+ * cálculo do resto da divisão por 11
129
+ * regra:
130
+
131
+ * resto < 2 → DV = 0
132
+ * caso contrário → DV = 11 - resto
133
+
134
+ Para o novo CNPJ alfanumérico:
135
+
136
+ * caracteres sĂŁo convertidos usando **ASCII - 48**
137
+
138
+ ---
139
+
140
+ ## 👨‍💻 Autor
141
+
142
+ Desenvolvido por **Thalys Mazzitelli Cotta**
143
+ đź”— https://github.com/Thalysinho
144
+
145
+ ---
146
+
147
+ ## 📄 Licença
148
+
149
+ Este projeto está sob a licença MIT.
150
+
151
+ ---
package/package.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@thalys.mazzitelli.cotta/cnpj-validator-br",
3
+ "version": "1.0.0",
4
+ "author": {
5
+ "name": "Thalys Mazzitelli Cotta",
6
+ "url": "https://github.com/Thalysinho"
7
+ },
8
+ "main": "src/index.js",
9
+ "scripts": {
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "keywords": ["cnpj", "validator", "brasil"],
13
+ "license": "ISC",
14
+ "description": ""
15
+ }
package/src/clean.js ADDED
@@ -0,0 +1,14 @@
1
+ // O clean.js: pega o valor que a pessoa digitou e devolve uma versão “limpa”, pronta para validar e formatar.
2
+ // entrada suja -> saĂ­da limpa
3
+ /*
4
+ 1- aceitar qualquer entrada
5
+ 2- transformar em string
6
+ 3- deixar tudo em maiĂşsculo
7
+ 4- remover tudo que nĂŁo for letra ou nĂşmero
8
+ */
9
+ function clean(value) {
10
+ if (value === null || value === undefined) return '';
11
+
12
+ return String(value).toUpperCase().replace(/[^0-9A-Z]/g, '');
13
+ }
14
+ module.exports = clean;
package/src/dv.js ADDED
@@ -0,0 +1,40 @@
1
+ // O dv.js é o coração da validação.
2
+ // -transformar cada caractere em valor numérico para o cálculo ( ASCII - 48 )
3
+ // -calcular os dĂ­gitos verificadores usando mĂłdulo 11
4
+ // RESUMO: pegar os caracteres e tranforma-los em nĂşmeros ( A -> 65 (tabela ASCII) - 48 = 17 ) e depois calcular os dĂ­gitos verificadores usando mĂłdulo 11.
5
+ /* DV = dĂ­gito verificador. (2 Ăşltimos dĂ­gitos do CNPJ)
6
+ os 12 primeiros caracteres formam a base
7
+ os 2 Ăşltimos sĂŁo os DVs
8
+ */
9
+
10
+ function charToValue(char) {
11
+ return char.charCodeAt(0) - 48;
12
+ }
13
+
14
+ function calculateDV(base, weights) {
15
+ let sum = 0;
16
+
17
+ for (let i = 0; i < base.length; i++) {
18
+ sum += charToValue(base[i]) * weights[i];
19
+ }
20
+
21
+ const remainder = sum % 11;
22
+
23
+ return remainder < 2 ? 0 : 11 - remainder;
24
+ }
25
+
26
+ function calculateCNPJDVs(base12) {
27
+ const firstWeights = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
28
+ const secondWeights = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
29
+
30
+ const firstDV = calculateDV(base12, firstWeights);
31
+ const secondDV = calculateDV(base12 + firstDV, secondWeights);
32
+
33
+ return `${firstDV}${secondDV}`;
34
+ }
35
+
36
+ module.exports = {
37
+ charToValue,
38
+ calculateDV,
39
+ calculateCNPJDVs,
40
+ };
package/src/format.js ADDED
@@ -0,0 +1,29 @@
1
+ // O format.js vai pegar o valor já digitado e devolver com a máscara visual do CNPJ.
2
+ // transforma isso: 12345678000195 em isso: 12.345.678/0001-95 // 12ABC34501DE35 em 12.ABC.345/01DE-35
3
+ /*
4
+ estrutura do CNPJ: XX.XXX.XXX/XXXX-XX
5
+ Então os separadores entram nessas posições:
6
+ depois do 2Âş caractere -> .
7
+ depois do 5Âş caractere -> .
8
+ depois do 8Âş caractere -> /
9
+ depois do 12Âş caractere -> -
10
+ */
11
+
12
+ const clean = require("./clean");
13
+
14
+ function format(value) {
15
+ const cleanedValue = clean(value).slice(0, 14);
16
+ let formattedValue = "";
17
+
18
+ for (let i = 0; i < cleanedValue.length; i++) {
19
+ if (i === 2 || i === 5) formattedValue += ".";
20
+ if (i === 8) formattedValue += "/";
21
+ if (i === 12) formattedValue += "-";
22
+
23
+ formattedValue += cleanedValue[i];
24
+ }
25
+
26
+ return formattedValue;
27
+ }
28
+
29
+ module.exports = format;
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ const clean = require("./clean");
2
+ const format = require("./format");
3
+ const validate = require("./validate");
4
+
5
+ module.exports = {
6
+ clean,
7
+ format,
8
+ validate,
9
+ };
@@ -0,0 +1,32 @@
1
+ /*
2
+ O validate.js compara o os DVs calculados com os DVs informados
3
+
4
+ Ele precisa:
5
+ limpar o valor
6
+ verificar se tem 14 caracteres
7
+ verificar se o formato básico é válido
8
+ separar base e DV informado
9
+ calcular o DV correto
10
+ comparar os dois
11
+ e retorna true ou false
12
+ */
13
+
14
+ const clean = require("./clean");
15
+ const { calculateCNPJDVs } = require("./dv");
16
+
17
+ function validate(value) {
18
+ const cleanedValue = clean(value);
19
+ const cnpjPattern = /^[A-Z0-9]{12}[0-9]{2}$/;
20
+
21
+ if (cleanedValue.length !== 14) return false;
22
+ if (!cnpjPattern.test(cleanedValue)) return false;
23
+ if (/^\d{14}$/.test(cleanedValue) && /^(\d)\1{13}$/.test(cleanedValue)) return false
24
+
25
+ const base12 = cleanedValue.slice(0, 12);
26
+ const informedDVs = cleanedValue.slice(12);
27
+ const calculatedDVs = calculateCNPJDVs(base12);
28
+
29
+ return informedDVs === calculatedDVs;
30
+ }
31
+
32
+ module.exports = validate;
@@ -0,0 +1,5 @@
1
+ const cnpj = require("../src");
2
+
3
+ console.log('Cleaned CNPJ: ' + cnpj.clean("12.ABC.345/01DE-35"));
4
+ console.log('Formatted CNPJ: ' + cnpj.format("12ABC34501DE35"));
5
+ console.log('Valid CNPJ: ' + cnpj.validate("12.345.678/0001-95"));