├── .github
├── FUNDING.yml
└── workflows
│ └── proposing-changes.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── composer.json
├── composer.lock
├── phpcs.xml
├── phpunit.xml.dist
├── src
└── validator-docs
│ ├── Contracts
│ └── ValidatorFormats.php
│ ├── Formats
│ ├── Certidao.php
│ ├── Cnpj.php
│ ├── Cpf.php
│ ├── CpfCnpj.php
│ └── Nis.php
│ ├── Rules
│ ├── Certidao.php
│ ├── Cnh.php
│ ├── Cnpj.php
│ ├── Cns.php
│ ├── Cpf.php
│ ├── Ddd.php
│ ├── InscricaoEstadual.php
│ ├── Nis.php
│ ├── Passaporte.php
│ ├── Placa.php
│ ├── Renavam.php
│ ├── Sanitization.php
│ └── TituloEleitoral.php
│ ├── Validator.php
│ ├── ValidatorFormats.php
│ └── ValidatorProvider.php
└── tests
├── Rules
└── RenavamTest.php
├── SanitizationTestCase.php
├── TestValidator.php
├── ValidatorFormatsTest.php
└── ValidatorTestCase.php
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: ['https://nubank.com.br/pagar/518o5/zVBzxd00Sb'] # Replace with up to 4 custom sponsorship URLs e.g.
13 |
--------------------------------------------------------------------------------
/.github/workflows/proposing-changes.yml:
--------------------------------------------------------------------------------
1 | name: "Proposing Changes"
2 |
3 | on:
4 | pull_request:
5 | branches: [ master, develop ]
6 |
7 | jobs:
8 | test:
9 | runs-on: ubuntu-latest
10 |
11 | steps:
12 | - uses: actions/checkout@v2
13 |
14 | - name: Setup PHP with Xdebug
15 | uses: shivammathur/setup-php@v2
16 | with:
17 | php-version: '8.1'
18 | coverage: xdebug
19 |
20 | - name: Validate composer.json and composer.lock
21 | run: composer validate
22 |
23 | - name: Cache Composer packages
24 | id: composer-cache
25 | uses: actions/cache@v2
26 | with:
27 | path: vendor
28 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
29 | restore-keys: |
30 | ${{ runner.os }}-php-
31 |
32 | - name: Install dependencies
33 | if: steps.composer-cache.outputs.cache-hit != 'true'
34 | run: composer install --prefer-dist --no-progress
35 |
36 | - name: Run Tests And Lint
37 | run: composer test
38 |
39 | - name: Upload coverage results to Coveralls
40 | env:
41 | COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
42 | run: |
43 | composer global require php-coveralls/php-coveralls
44 | php-coveralls --coverage_clover=build/logs/clover.xml -v
45 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor
2 | composer.phar
3 | .DS_Store
4 | .idea/
5 | /build
6 | *.cache
7 | docker-compose.yml
8 | .phpcs-cache
9 | .phpunit.result.cache
10 | phpunit.xml
11 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | A partir da versão 3.5.1 nosso modelo de logs é baseado em [mantenha um changelog](https://keepachangelog.com/pt-BR/1.0.0/) e o
4 | nosso versionamento é [semântico](https://semver.org/lang/pt-BR/).
5 |
6 | ## [3.11.1](https://github.com/geekcom/validator-docs/compare/3.11.0...3.11.1)
7 |
8 | ## Novidades - Por hora revertemos as melhorias na validação de CPF
9 |
10 | - Revert:
11 | - Melhorias na validação de CPF.
12 |
13 | ## [3.11.0](https://github.com/geekcom/validator-docs/compare/3.10.0...3.11.0)
14 |
15 | ## Novidades
16 |
17 | - Atualizado:
18 | - Melhorias na validação de CPF.
19 |
20 | ## [3.10.0](https://github.com/geekcom/validator-docs/compare/3.9.0...3.10.0)
21 |
22 | ## Novidades - Validação de passaporte brasileiro
23 |
24 | - Adicionado:
25 | - Agora é possivel validar passaporte brasileiro, consulte a doc para maiores detalhes.
26 | - Atualizado:
27 | - A documentação foi atualizada.
28 |
29 | ## [3.9.0](https://github.com/geekcom/validator-docs/compare/3.8.0...3.9.0)
30 |
31 | ## Novidades - Testado com Laravel 10
32 |
33 | - Corrigido:
34 | - A mensagem de retorno em caso de erro de validação de DDD.
35 | - Atualizado:
36 | - A documentação foi atualizada.
37 |
38 | ## [3.8.0](https://github.com/geekcom/validator-docs/compare/3.7.1...3.8.0)
39 |
40 | ## Novidades
41 |
42 | - Melhorias:
43 | - Os testes de validação de formatos foram melhorados;
44 | - Diversas pequenas melhorias foram adicionadas;
45 | - A doc foi melhorada.
46 |
47 | ## [3.7.1](https://github.com/geekcom/validator-docs/compare/3.7.0...3.7.1)
48 |
49 | ## Novidades
50 |
51 | - Corrigido:
52 | - Um dos valores usados nos testes de validação de RENAVAM;
53 |
54 | ## [3.7.0](https://github.com/geekcom/validator-docs/compare/3.6.0...3.7.0)
55 |
56 | ## Novidades
57 |
58 | - Atualizado:
59 | - As regras de validação de RENAVAM foram reescritas;
60 | - Os testes de validação de RENAVAM foram atualizados.
61 |
62 | ## [3.6.0](https://github.com/geekcom/validator-docs/compare/3.5.3...3.6.0)
63 |
64 | ## Novidades
65 |
66 | - Corrigido:
67 | - A documentação referente a validação de inscrição estadual;
68 | - O arquivo `composer.lock` foi removido do `.gitignore`;
69 | - A opção depreciada do composer `--no-suggest`, foi removida do workflow Github actions.
70 | - Atualizado:
71 | - A versão mínima do PHP, e algumas dependências do projeto;
72 | - As classes de validação de formatos de documentos NIS e CNPJ;
73 | - O arquivo `phpunit.xml` foi adicionado ao `.gitignore`;
74 | - Suporte a badge de build do Github actions;
75 | - Suporte a badge de Coverage Status do coveralls.io.
76 | - Removido:
77 | - O arquivo `phpunit.xml`;
78 | - O suporte a travisCI.
79 | - Adicionado:
80 | - O arquivo `phpunit.xml.dist`;
81 | - A possibilidade de rodar testes de unidade via comando `composer testdox`;
82 |
83 | ## [3.5.4](https://github.com/geekcom/validator-docs/compare/3.5.3...3.5.4)
84 |
85 | ## Commits
86 |
87 | - Consertado: link para o travis-ci no README.md [`e4c9dcd`](https://github.com/geekcom/validator-docs/commit/e4c9dcd124795ce9dd6a36d1114db9c2d7b999db)
88 |
89 | ## [3.5.3](https://github.com/geekcom/validator-docs/compare/3.5.2...3.5.3)
90 |
91 | ## Commits
92 |
93 | - Modificado: link para geração de documento [`94064a9`](https://github.com/geekcom/validator-docs/commit/94064a98379dca1e781bd358e4c10d7a1cff0020)
94 | - Consertado: retirado informação duplicada para Inscrição Estadual do README [`94064a9`](https://github.com/geekcom/validator-docs/commit/94064a98379dca1e781bd358e4c10d7a1cff0020)
95 | - Consertado: valida formato do documento apenas se valor é informado. [`424fc22c`](https://github.com/geekcom/validator-docs/commit/424fc22c9865a77e6c27a9a26e4ed8dd9baf20eb)
96 |
97 | ## [3.5.2](https://github.com/geekcom/validator-docs/compare/3.5.1...3.5.2)
98 |
99 | ## Commits
100 |
101 | - Adicionado: verificação de DDD. [`52bb67a`](https://github.com/geekcom/validator-docs/commit/52bb67a51bf6c36f5aef00fb9429203bfe4d4ad3)
102 | - Adicionado: mensagem para a verificação de DDD. [`52bb67a`](https://github.com/geekcom/validator-docs/commit/52bb67a51bf6c36f5aef00fb9429203bfe4d4ad3)
103 | - Modificado: teste no PHP 8, dependências foram atualizadas. [`a0005e1`](https://github.com/geekcom/validator-docs/commit/a0005e168eb2eca0da06d36ae92b8976c4195766)
104 | - Modificado: fix Sanitization class to deal with null values. [`d57c8e9`](https://github.com/geekcom/validator-docs/commit/d57c8e9076769d2e978d5bd3a8fbd470980b5bbb)
105 | - Modificado/Adicionado: melhora coverage para Renavam. [`574114d`](https://github.com/geekcom/validator-docs/commit/574114d29ef5d98784972aafe7213fcf6bac4d8e)
106 | - Consertado: resolve erro com sanitize. [`a6d33e5`](https://github.com/geekcom/validator-docs/commit/a6d33e54a66090ffb485e7385e9c1fc40ca4e9da)
107 |
108 | ## [3.5.1](https://github.com/geekcom/validator-docs/compare/3.5.0...3.5.1)
109 |
110 | ## Commits
111 |
112 | - Modificado: Atualizar versão da lib na doc. [`e61829b`](https://github.com/geekcom/validator-docs/commit/e61829be54353c0335db425962d7c2e9075d727f)
113 | - Corrigido: validação de Placa não precisa de sanitization. [`d5a0e7b`](https://github.com/geekcom/validator-docs/commit/d5a0e7be832003332395b5e3eac2a58f879ca060)
114 |
115 | ---
116 |
117 |
118 |
119 |
120 | ## [3.5.0]
121 |
122 | - [#100] fix tests, melhorias gerais, Thanks to [@geekcom]
123 | - [#102] Sync master with develop, Thanks to [@geekcom]
124 | - [#77] Merge pull request [#76] from geekcom/master, Thanks to [@geekcom]
125 | - [#62] melhorias para cobrir PSR-12, Thanks to [@geekcom]
126 | - [#63] remover suporte ao scrutinizerCI, Thanks to [@geekcom]
127 | - [#64] atualizado e-mail do autor, Thanks to [@geekcom]
128 | - [#65] Atualizacao de nomes de testes, Thanks to [@geekcom]
129 | - [#67] Update README.md, Thanks to [@geekcom]
130 | - [#76] Sync master com develop, Thanks to [@geekcom]
131 | - [#79] Merge pull request [#78] from geekcom/master, Thanks to [@geekcom]
132 | - [#78] Sync master com develop, Thanks to [@geekcom]
133 | - [#101] Sync, Thanks to [@geekcom]
134 | - [#80] Merge pull request [#79] from geekcom/develop, Thanks to [@geekcom]
135 | - [#81] Merge pull request [#80] from geekcom/master, Thanks to [@geekcom]
136 | - [#82] Update README.md, Thanks to [@geekcom]
137 | - [#83] Merge pull request [#82] from geekcom/master, Thanks to [@geekcom]
138 | - [#85] Sync, Thanks to [@geekcom]
139 | - [#86] Merge pull request [#85] from geekcom/master, Thanks to [@geekcom]
140 | - [#90] Adicionando validação de Renavam, Thanks to [@rafaelneris]
141 | - [#93] Valida Inscrição Estadual para cada Unidade Federativa, Thanks to [@thicolares]
142 | - [#95] Validação Placa, Thanks to [@omarkdev]
143 | - [#96] Corrige estilo de código na classe do Renavam, Thanks to [@omarkdev]
144 | - [#97] Cria workflow no github para rodar testes ao propor novo pull request, Thanks to [@omarkdev]
145 | - [#98] Sync master into develop, Thanks to [@geekcom]
146 | - [#99] Merge pull request [#98] from geekcom/master, Thanks to [@geekcom]
147 | - [#61] update CHANGELOG.md, Thanks to [@geekcom]
148 |
149 |
150 |
151 |
152 |
153 | ## [3.4.0]
154 |
155 | - [#60] atualizados, CI, Thanks to [@geekcom]
156 | - [#59] suporte a coverage, Thanks to [@geekcom]
157 | - [#58] suporte a travisCI, Thanks to [@geekcom]
158 | - [#57] Develop, Thanks to [@geekcom]
159 | - [#56] Develop, Thanks to [@geekcom]
160 |
161 |
162 |
163 |
164 |
165 | ## [3.3.2]
166 |
167 | - [#55] Igualando develop e master, Thanks to [@geekcom]
168 | - [#54] Arrumando cnh, Thanks to [@MrEko]
169 | - [#51] update CHANGELOG.md, Thanks to [@geekcom]
170 |
171 |
172 |
173 |
174 |
175 | ## [3.3.1]
176 |
177 | - [#50] minor correction, update doc, Thanks to [@geekcom]
178 |
179 |
180 |
181 |
182 |
183 | ## [3.3.0]
184 |
185 | - [#49] solved: complexity, update: tests, Thanks to [@geekcom]
186 |
187 |
188 |
189 |
190 |
191 | ## Unreleased
192 |
193 | - [#48] added support for changelogs, Thanks to [@geekcom]
194 | - [#45] fixing "Unparenthesized is deprecated" error, Thanks to [@kidh0]
195 | - [#17] fix: erro em phpunit.xml, melhorias nos testes, namespace para testes, Thanks to [@geekcom]
196 | - [#25] Melhorias de leitura nos códigos, Thanks to [@geekcom]
197 | - [#2] Alteração da função validateCnpj para impedir que o Cnpj 00.000.000/0…, Thanks to [@andrergcosta]
198 | - [#3] Criada as funções validateFormatoCpfCnpj e validateCpfCnpj, Thanks to [@andrergcosta]
199 | - [#4] Inclusão do exemplo para validação de CPF/CNPJ no arquivo readme, Thanks to [@andrergcosta]
200 | - [#5] Validar título eleitor, Thanks to [@andrergcosta]
201 | - [#8] Faltando parâmetro $attributes em ValidatorProvider., Thanks to [@setefocos]
202 | - [#11] nova badge e melhoria no readme.me, Thanks to [@geekcom]
203 | - [#12] scrutinizer CI, Thanks to [@geekcom]
204 | - [#19] Criação da função para verificar PIS/PASEP/NIS/NIT, Thanks to [@lordantonelli]
205 | - [#20] Master from develop, Thanks to [@geekcom]
206 | - [#21] Merge pull request [#20] from geekcom/master, Thanks to [@geekcom]
207 | - [#23] update docs, minor corrections, Thanks to [@geekcom]
208 | - [#24] update docs, Thanks to [@geekcom]
209 | - [#30] update scrutinizer CI check, Thanks to [@geekcom]
210 | - [#27] atualizacao para Laravel 6, Thanks to [@geekcom]
211 | - [#47] Merge pull request [#46] from geekcom/master, Thanks to [@geekcom]
212 | - [#31] Atualização dos requisitos e testes, Thanks to [@victorhsanjos]
213 | - [#32] master into develop, Thanks to [@geekcom]
214 | - [#33] Merge pull request [#32] from geekcom/master, Thanks to [@geekcom]
215 | - [#35] auto-discover composer, Thanks to [@geekcom]
216 | - [#37] Adicionando validação do Cartão Nacional de Saúde, Thanks to [@MrEko]
217 | - [#38] Merge, Thanks to [@geekcom]
218 | - [#39] Merge pull request [#38] from geekcom/master, Thanks to [@geekcom]
219 | - [#40] melhorias de documentacao e sintaxe, v3.0.0, Thanks to [@geekcom]
220 | - [#41] Validação de Certidão de Nascimento, Casamento ou Óbito, Thanks to [@MrEko]
221 | - [#42] merge master into develop, Thanks to [@geekcom]
222 | - [#43] Merge pull request [#42] from geekcom/master, Thanks to [@geekcom]
223 | - [#44] melhoria na validacao de CNH,strict_types PHP ativado, Thanks to [@geekcom]
224 | - [#46] merge master inte develop, Thanks to [@geekcom]
225 | - [#1] Update README.md, Thanks to [@yvescabral]
226 |
227 |
228 |
229 | [#48]: https://github.com/geekcom/validator-docs/pull/48
230 | [#47]: https://github.com/geekcom/validator-docs/pull/47
231 | [#46]: https://github.com/geekcom/validator-docs/pull/46
232 | [#45]: https://github.com/geekcom/validator-docs/pull/45
233 | [#44]: https://github.com/geekcom/validator-docs/pull/44
234 | [#43]: https://github.com/geekcom/validator-docs/pull/43
235 | [#42]: https://github.com/geekcom/validator-docs/pull/42
236 | [#41]: https://github.com/geekcom/validator-docs/pull/41
237 | [#40]: https://github.com/geekcom/validator-docs/pull/40
238 | [#39]: https://github.com/geekcom/validator-docs/pull/39
239 | [#38]: https://github.com/geekcom/validator-docs/pull/38
240 | [#37]: https://github.com/geekcom/validator-docs/pull/37
241 | [#35]: https://github.com/geekcom/validator-docs/pull/35
242 | [#33]: https://github.com/geekcom/validator-docs/pull/33
243 | [#32]: https://github.com/geekcom/validator-docs/pull/32
244 | [#31]: https://github.com/geekcom/validator-docs/pull/31
245 | [#30]: https://github.com/geekcom/validator-docs/pull/30
246 | [#27]: https://github.com/geekcom/validator-docs/pull/27
247 | [#25]: https://github.com/geekcom/validator-docs/pull/25
248 | [#24]: https://github.com/geekcom/validator-docs/pull/24
249 | [#23]: https://github.com/geekcom/validator-docs/pull/23
250 | [#21]: https://github.com/geekcom/validator-docs/pull/21
251 | [#20]: https://github.com/geekcom/validator-docs/pull/20
252 | [#19]: https://github.com/geekcom/validator-docs/pull/19
253 | [#17]: https://github.com/geekcom/validator-docs/pull/17
254 | [#12]: https://github.com/geekcom/validator-docs/pull/12
255 | [#11]: https://github.com/geekcom/validator-docs/pull/11
256 | [#8]: https://github.com/geekcom/validator-docs/pull/8
257 | [#5]: https://github.com/geekcom/validator-docs/pull/5
258 | [#4]: https://github.com/geekcom/validator-docs/pull/4
259 | [#3]: https://github.com/geekcom/validator-docs/pull/3
260 | [#2]: https://github.com/geekcom/validator-docs/pull/2
261 | [#1]: https://github.com/geekcom/validator-docs/pull/1
262 | [@yvescabral]: https://github.com/yvescabral
263 | [@victorhsanjos]: https://github.com/victorhsanjos
264 | [@setefocos]: https://github.com/setefocos
265 | [@lordantonelli]: https://github.com/lordantonelli
266 | [@kidh0]: https://github.com/kidh0
267 | [@geekcom]: https://github.com/geekcom
268 | [@andrergcosta]: https://github.com/andrergcosta
269 | [@MrEko]: https://github.com/MrEko
270 | [#49]: https://github.com/geekcom/validator-docs/pull/49
271 | [#50]: https://github.com/geekcom/validator-docs/pull/50
272 | [#55]: https://github.com/geekcom/validator-docs/pull/55
273 | [#54]: https://github.com/geekcom/validator-docs/pull/54
274 | [#51]: https://github.com/geekcom/validator-docs/pull/51
275 | [#102]: https://github.com/geekcom/validator-docs/pull/102
276 | [#101]: https://github.com/geekcom/validator-docs/pull/101
277 | [#100]: https://github.com/geekcom/validator-docs/pull/100
278 | [#99]: https://github.com/geekcom/validator-docs/pull/99
279 | [#98]: https://github.com/geekcom/validator-docs/pull/98
280 | [#97]: https://github.com/geekcom/validator-docs/pull/97
281 | [#96]: https://github.com/geekcom/validator-docs/pull/96
282 | [#95]: https://github.com/geekcom/validator-docs/pull/95
283 | [#93]: https://github.com/geekcom/validator-docs/pull/93
284 | [#90]: https://github.com/geekcom/validator-docs/pull/90
285 | [#86]: https://github.com/geekcom/validator-docs/pull/86
286 | [#85]: https://github.com/geekcom/validator-docs/pull/85
287 | [#83]: https://github.com/geekcom/validator-docs/pull/83
288 | [#82]: https://github.com/geekcom/validator-docs/pull/82
289 | [#81]: https://github.com/geekcom/validator-docs/pull/81
290 | [#80]: https://github.com/geekcom/validator-docs/pull/80
291 | [#79]: https://github.com/geekcom/validator-docs/pull/79
292 | [#78]: https://github.com/geekcom/validator-docs/pull/78
293 | [#77]: https://github.com/geekcom/validator-docs/pull/77
294 | [#76]: https://github.com/geekcom/validator-docs/pull/76
295 | [#75]: https://github.com/geekcom/validator-docs/pull/75
296 | [#67]: https://github.com/geekcom/validator-docs/pull/67
297 | [#65]: https://github.com/geekcom/validator-docs/pull/65
298 | [#64]: https://github.com/geekcom/validator-docs/pull/64
299 | [#63]: https://github.com/geekcom/validator-docs/pull/63
300 | [#62]: https://github.com/geekcom/validator-docs/pull/62
301 | [#61]: https://github.com/geekcom/validator-docs/pull/61
302 | [@thicolares]: https://github.com/thicolares
303 | [@rafaelneris]: https://github.com/rafaelneris
304 | [@omarkdev]: https://github.com/omarkdev
305 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Daniel Rodrigues Lima
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Validator Docs - Brasil
2 | _Biblioteca PHP para validação de documentos do Brasil usando **Laravel**_
3 |
4 | 
5 | [](https://coveralls.io/github/geekcom/validator-docs)
6 | [](https://github.com/phpstan/phpstan)
7 | [](https://packagist.org/packages/geekcom/validator-docs)
8 | [](https://packagist.org/packages/geekcom/validator-docs)
9 | [](https://packagist.org/packages/geekcom/validator-docs)
10 |
11 | > ### Por favor, considere **[fazer uma doação](https://nubank.com.br/pagar/518o5/zVBzxd00Sb)**, apoie nossas atividades
12 |
13 | > Para a versão legada compatível com Laravel 5 consulte o branch https://github.com/geekcom/validator-docs/tree/5.x.x
14 |
15 | ## Recursos
16 | - Validar qualquer documento do Brasil;
17 | - Código testado e confiável;
18 | - Open Source;
19 | - Usado por milhares de sistemas;
20 | - Aprovado pela comunidade Laravel.
21 |
22 | ## Instalação
23 | No arquivo `composer.json`, adicione validator-docs como dependência do seu projeto:
24 |
25 | ```
26 | "require": {
27 | "geekcom/validator-docs" : "^3.9"
28 | },
29 | ```
30 |
31 | Depois execute:
32 |
33 | ```bash
34 | composer install
35 | ```
36 |
37 | Ou simplesmente execute o comando:
38 |
39 | ```bash
40 | composer require geekcom/validator-docs
41 | ```
42 |
43 | ----------------------------------------------------------------------------------------------------------------------------
44 |
45 | ## Testes
46 | Para executar os testes, basta fazer o seguinte:
47 |
48 | * Instale as dependências do projeto;
49 | ```bash
50 | composer install
51 | ```
52 | * Execute os testes.
53 | ```bash
54 | composer test
55 | ```
56 |
57 | ----------------------------------------------------------------------------------------------------------------------------
58 |
59 | ## Como usar a biblioteca
60 | Agora que os métodos de validação validator-docs Brasil estão disponíveis, será possível usar da seguinte forma:
61 |
62 | * **cpf** - Verifica se um CPF é valido;
63 |
64 | ```php
65 | $this->validate($request, [
66 | 'cpf' => 'required|cpf',
67 | ]);
68 | ```
69 |
70 | * **cnpj** - Verifica se um CNPJ é valido;
71 |
72 | ```php
73 | $this->validate($request, [
74 | 'cnpj' => 'required|cnpj',
75 | ]);
76 | ```
77 |
78 | * **cnh** - Verifica se uma CNH (Carteira Nacional de Habilitação) é válida;
79 |
80 | ```php
81 | $this->validate($request, [
82 | 'cnh' => 'required|cnh',
83 | ]);
84 | ```
85 |
86 | * **passaporte** - Verifica se uma Passaporte Brasileiro é válido;
87 |
88 | ```php
89 | $this->validate($request, [
90 | 'passaporte' => 'required|passaporte',
91 | ]);
92 | ```
93 |
94 | * **titulo_eleitor** - Verifica se um Título Eleitoral é válido;
95 |
96 | ```php
97 | $this->validate($request, [
98 | 'titulo_eleitor' => 'required|titulo_eleitor',
99 | ]);
100 | ```
101 |
102 | * **cpf_cnpj** - Verifica se um CPF ou CNPJ é válido;
103 |
104 | ```php
105 | $this->validate($request, [
106 | 'cpf_cnpj' => 'required|cpf_cnpj',
107 | ]);
108 | ```
109 |
110 | * **inscricao_estadual** - Verifica se uma Inscrição Estadual é valida para uma Unidade Federativa(UF)/Estado;
111 |
112 | ```php
113 | $this->validate($request, [
114 | 'inscricao_estadual' => 'required|inscricao_estadual:UF',
115 | ]);
116 | ```
117 |
118 | * **nis** - Verifica se um PIS/PASEP/NIT/NIS é válido;
119 |
120 | ```php
121 | $this->validate($request, [
122 | 'nis' => 'required|nis',
123 | ]);
124 | ```
125 |
126 | * **cns** - Verifica se um Cartão Nacional de Saúde (CNS) é válido;
127 |
128 | ```php
129 | $this->validate($request, [
130 | 'cns' => 'required|cns',
131 | ]);
132 | ```
133 |
134 | * **certidao** - Verifica se uma certidão de nascimento/casamento/óbito é válida;
135 |
136 | ```php
137 | $this->validate($request, [
138 | 'certidao' => 'required|certidao',
139 | ]);
140 | ```
141 |
142 | * **renavam** - Verifica se um Registro Nacional de Veículos Automotores (RENAVAM) é válido;
143 |
144 | ```php
145 | $this->validate($request, [
146 | 'renavam' => 'required|renavam',
147 | ]);
148 | ```
149 |
150 | * **placa** - Verifica se a PLACA de um veículo é válida;
151 |
152 | ```php
153 | $this->validate($request, [
154 | 'placa' => 'required|placa',
155 | ]);
156 | ```
157 |
158 | * **ddd** - Verifica se um número de [DDD](https://pt.wikipedia.org/wiki/Discagem_direta_%C3%A0_dist%C3%A2ncia) é válido;
159 |
160 | ```php
161 | $this->validate($request, [
162 | 'ddd' => 'required|ddd',
163 | ]);
164 | ```
165 |
166 | * **formato_cnpj** - Verifica se o formato`(99.999.999/9999-99)` de um CNPJ é válido;
167 |
168 | ```php
169 | $this->validate($request, [
170 | 'formato_cnpj' => 'required|formato_cnpj',
171 | ]);
172 | ```
173 |
174 | * **formato_cpf** - Verifica se o formato(`999.999.999-99`) de um CPF é válido;
175 |
176 | ```php
177 | $this->validate($request, [
178 | 'formato_cpf' => 'required|formato_cpf',
179 | ]);
180 | ```
181 |
182 | * **formato_cpf_cnpj** - Verifica se o formato de um CPF ou de um CNPJ é válido;
183 |
184 | ```php
185 | $this->validate($request, [
186 | 'formato_cpf_cnpj' => 'required|formato_cpf_cnpj',
187 | ]);
188 | ```
189 |
190 | * **formato_nis** - Verifica se o formato(`999.99999-99.9`) de um PIS/PASEP/NIT/NIS é válido;
191 |
192 | ```php
193 | $this->validate($request, [
194 | 'formato_nis' => 'required|formato_nis',
195 | ]);
196 | ```
197 |
198 | * **formato_certidao** - Verifica se o formato(`99999.99.99.9999.9.99999.999.9999999-99` ou `99999 99 99 9999 9 99999 999 9999999 99`), de uma certidão é válida.
199 |
200 | ```php
201 | $this->validate($request, [
202 | 'formato_certidao' => 'required|formato_certidao',
203 | ]);
204 | ```
205 | ----------------------------------------------------------------------------------------------------------------------------
206 |
207 | ## Combinando validação e formato
208 | No exemplo abaixo, fazemos um teste onde verificamos a formatação e a validade de um CPF ou CNPJ, para os casos onde a informação deve ser salva em um mesmo atributo:
209 |
210 | ```php
211 | $this->validate($request, [
212 | 'cpf_or_cnpj' => 'formato_cpf_cnpj|cpf_cnpj',
213 | ]);
214 | ```
215 |
216 | ----------------------------------------------------------------------------------------------------------------------------
217 |
218 | ## Exemplo de uso em um controller
219 | Método de validação de exemplo em um controller com todas as possibilidades de validação
220 |
221 | ```php
222 | public function store(Request $request)
223 | {
224 | $data = $request->all();
225 |
226 | $this->validate($request, [
227 | 'cpf' => 'required|cpf',
228 | 'cnpj' => 'required|cnpj',
229 | 'cnh' => 'required|cnh',
230 | 'titulo_eleitor' => 'required|titulo_eleitor',
231 | 'nis' => 'required|nis',
232 | 'cns' => 'required|cns',
233 | 'ddd' => 'required|ddd',
234 | 'renavam' => 'required|renavam',
235 | 'placa' => 'required|placa',
236 | 'certidao' => 'required|certidao',
237 | 'inscricao_estadual' => 'required|inscricao_estadual:SP',
238 | 'passaporte' => 'required|passaporte',
239 | ]);
240 |
241 | dd($data);
242 | }
243 | ```
244 | **Observe que para validar uma inscrição estadual é necessário informar a [UF](https://pt.wikipedia.org/wiki/Unidades_federativas_do_Brasil)**
245 |
246 | ----------------------------------------------------------------------------------------------------------------------------
247 |
248 | ## Geradores de documentos para testes
249 | * **CNH** - http://4devs.com.br/gerador_de_cnh
250 | * **TÍTULO ELEITORAL** - http://4devs.com.br/gerador_de_titulo_de_eleitor
251 | * **CNPJ** - https://geradornv.com.br/gerador-cnpj/
252 | * **CPF** - https://geradornv.com.br/gerador-cpf/
253 | * **NIS** - https://www.4devs.com.br/gerador_de_pis_pasep
254 | * **CNS** - https://geradornv.com.br/gerador-cns/
255 | * **CERTIDÕES** - https://www.4devs.com.br/gerador_numero_certidoes
256 | * **INSCRIÇÃO ESTADUAL** - https://www.4devs.com.br/gerador_de_inscricao_estadual
257 | * **RENAVAM** - https://www.4devs.com.br/gerador_de_renavam
258 | * **PLACA** - https://www.4devs.com.br/gerador_de_placa_automoveis
259 | * **Passaporte Brasileiro** - https://geradornv.com.br/gerador-passaporte/
260 |
261 | Fique a vontade para contribuir de qualquer forma.
262 |
263 | Caso tenha alguma dúvida ou encontre algum bug, abra uma [issue](https://github.com/geekcom/validator-docs/issues) ou pesquise por issues antigas.
264 |
265 | ## [Contribuidores](https://github.com/geekcom/validator-docs/graphs/contributors)
266 | Contribuições de qualquer tipo são bem-vindas!
267 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "geekcom/validator-docs",
3 | "description": "Biblioteca PHP para validação de documentos do Brasil usando Laravel",
4 | "license": "MIT",
5 | "authors": [
6 | {
7 | "name": "Daniel Rodrigues Lima",
8 | "email": "geekcom@php.net"
9 | }
10 | ],
11 | "require": {
12 | "php": "^7.3|^8.0",
13 | "thiagocfn/inscricaoestadual": "^1.1"
14 | },
15 | "require-dev": {
16 | "phpunit/phpunit": "^8.4|^9.4",
17 | "orchestra/testbench": "^6.0",
18 | "php-coveralls/php-coveralls": "^2.5",
19 | "squizlabs/php_codesniffer": "*",
20 | "phpstan/phpstan": "^1.4"
21 | },
22 | "autoload": {
23 | "psr-4": {
24 | "geekcom\\ValidatorDocs\\": "src/validator-docs"
25 | }
26 | },
27 | "autoload-dev": {
28 | "psr-4": {
29 | "geekcom\\ValidatorDocs\\Tests\\": "tests"
30 | }
31 | },
32 | "extra": {
33 | "laravel": {
34 | "providers": [
35 | "geekcom\\ValidatorDocs\\ValidatorProvider"
36 | ]
37 | }
38 | },
39 | "scripts": {
40 | "phpcs": "phpcs --standard=PSR12 -n src",
41 | "phpstan": "phpstan analyse src --level 0",
42 | "phpcbf": "phpcbf --standard=PSR12 -n src",
43 | "unit": "phpunit",
44 | "testdox": "phpunit --testdox",
45 | "test": [
46 | "@phpcs",
47 | "@phpstan",
48 | "@unit"
49 | ]
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/phpcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | ^/tests/*
12 |
13 | src
14 |
15 |
16 |
--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | ./src/
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | ./tests/
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/validator-docs/Contracts/ValidatorFormats.php:
--------------------------------------------------------------------------------
1 | 0;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/validator-docs/Formats/Cnpj.php:
--------------------------------------------------------------------------------
1 | 0;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/validator-docs/Formats/Cpf.php:
--------------------------------------------------------------------------------
1 | 0;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/validator-docs/Formats/CpfCnpj.php:
--------------------------------------------------------------------------------
1 | validateFormat($value) || $cnpj->validateFormat($value);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/validator-docs/Formats/Nis.php:
--------------------------------------------------------------------------------
1 | 0;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Certidao.php:
--------------------------------------------------------------------------------
1 | sanitize($value);
22 |
23 | if (!preg_match("/[0-9]{32}/", $certidao)) {
24 | return false;
25 | }
26 |
27 | $num = substr($certidao, 0, -2);
28 | $dv = substr($certidao, -2);
29 |
30 | $dv1 = $this->somaPonderadaCertidao($num) % 11;
31 | $dv1 = $dv1 > 9 ? 1 : $dv1;
32 | $dv2 = $this->somaPonderadaCertidao($num . $dv1) % 11;
33 | $dv2 = $dv2 > 9 ? 1 : $dv2;
34 |
35 | // Compara o dv recebido com os dois numeros calculados
36 | if ($dv === $dv1 . $dv2) {
37 | return true;
38 | }
39 |
40 | return false;
41 | }
42 |
43 | private function somaPonderadaCertidao($value): int
44 | {
45 | $soma = 0;
46 |
47 | $multiplicador = 32 - mb_strlen($value);
48 |
49 | for ($i = 0; $i < mb_strlen($value); $i++) {
50 | $soma += $value[$i] * $multiplicador;
51 |
52 | $multiplicador += 1;
53 | $multiplicador = $multiplicador > 10 ? 0 : $multiplicador;
54 | }
55 |
56 | return $soma;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Cnh.php:
--------------------------------------------------------------------------------
1 | sanitize($value);
23 |
24 | if (mb_strlen($value) != 11 || ((int) $value === 0)) {
25 | return false;
26 | }
27 |
28 | $parcial = substr($value, 0, 9);
29 |
30 | for ($i = 0 , $j = 2, $s = 0; $i < mb_strlen($parcial); $i++, $j++) {
31 | $s += (int) $parcial[$i] * $j;
32 | }
33 |
34 | $resto = $s % 11;
35 | if ($resto <= 1) {
36 | $dv1 = 0;
37 | } else {
38 | $dv1 = 11 - $resto;
39 | }
40 |
41 | $parcial = $dv1 . $parcial;
42 |
43 | for ($i = 0, $j = 2, $s = 0; $i < mb_strlen($parcial); $i++, $j++) {
44 | $s += (int) $parcial[$i] * $j;
45 | }
46 |
47 | $resto = $s % 11;
48 | if ($resto <= 1) {
49 | $dv2 = 0;
50 | } else {
51 | $dv2 = 11 - $resto;
52 | }
53 |
54 | return $dv1 . $dv2 == substr($value, -2);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Cnpj.php:
--------------------------------------------------------------------------------
1 | sanitize($value);
15 |
16 | if (mb_strlen($c) != 14 || preg_match("/^{$c[0]}{14}$/", $c)) {
17 | return false;
18 | }
19 |
20 | $b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
21 |
22 | for (
23 | $i = 0, $n = 0; $i < 12; $n += $c[$i] * $b[++$i]
24 | ) {
25 | }
26 |
27 | if ($c[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
28 | return false;
29 | }
30 |
31 | for (
32 | $i = 0, $n = 0; $i <= 12; $n += $c[$i] * $b[$i++]
33 | ) {
34 | }
35 |
36 | if ($c[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
37 | return false;
38 | }
39 |
40 | return true;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Cns.php:
--------------------------------------------------------------------------------
1 | sanitize($value);
15 |
16 | // CNSs definitivos começam em 1 ou 2 / CNSs provisórios em 7, 8 ou 9
17 | if (preg_match("/[1-2][0-9]{10}00[0-1][0-9]/", $cns) || preg_match("/[7-9][0-9]{14}/", $cns)) {
18 | return $this->somaPonderadaCns($cns) % 11 == 0;
19 | }
20 |
21 | return false;
22 | }
23 |
24 | private function somaPonderadaCns($value): int
25 | {
26 | $soma = 0;
27 |
28 | for ($i = 0; $i < mb_strlen($value); $i++) {
29 | $soma += $value[$i] * (15 - $i);
30 | }
31 |
32 | return $soma;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Cpf.php:
--------------------------------------------------------------------------------
1 | sanitize($value);
15 |
16 | if (mb_strlen($c) != 11 || preg_match("/^{$c[0]}{11}$/", $c)) {
17 | return false;
18 | }
19 |
20 | for (
21 | $s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--
22 | ) {
23 | }
24 |
25 | if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
26 | return false;
27 | }
28 |
29 | for (
30 | $s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--
31 | ) {
32 | }
33 |
34 | if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
35 | return false;
36 | }
37 |
38 | return true;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Ddd.php:
--------------------------------------------------------------------------------
1 | sanitizeSiglaUf($parameters[0]);
20 | $inscricaoEstadual = $this->sanitize($value);
21 |
22 | return Validador::check($siglaUf, $inscricaoEstadual);
23 | }
24 |
25 | /**
26 | * @param mixed $siglaUf
27 | * @return false|string|string[]
28 | */
29 | private function sanitizeSiglaUf($siglaUf)
30 | {
31 | return mb_strtoupper($siglaUf);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Nis.php:
--------------------------------------------------------------------------------
1 | sanitize($value));
16 |
17 | if (mb_strlen($nis) != 11 || preg_match("/^{$nis[0]}{11}$/", $nis)) {
18 | return false;
19 | }
20 |
21 | for ($d = 0, $p = 2, $c = 9; $c >= 0; $c--, ($p < 9) ? $p++ : $p = 2) {
22 | $d += $nis[$c] * $p;
23 | }
24 |
25 | return ($nis[10] == (((10 * $d) % 11) % 10));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Passaporte.php:
--------------------------------------------------------------------------------
1 | 0;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Placa.php:
--------------------------------------------------------------------------------
1 | 0;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Renavam.php:
--------------------------------------------------------------------------------
1 | sanitize((string) $renavam);
24 | if (!$this->renavamHasCorrectLength($renavam)) {
25 | return false;
26 | }
27 |
28 | $realLastDigit = $this->getRealLastDigit($renavam);
29 | $informedLastDigit = (int) substr($renavam, strlen($renavam) - 1, strlen($renavam));
30 |
31 | return $realLastDigit === $informedLastDigit;
32 | }
33 |
34 |
35 | /**
36 | * Sanitize the renavam value.
37 | *
38 | * @param $value
39 | * @return string
40 | */
41 | public function sanitize($value): string
42 | {
43 | $renavam = parent::sanitize((string) $value);
44 | if (preg_match("/^([0-9]{9})$/", $renavam)) {
45 | $renavam = '00' . $renavam;
46 | }
47 |
48 | if (preg_match("/^([0-9]{10})$/", $renavam)) {
49 | $renavam = '0' . $renavam;
50 | }
51 |
52 | return $renavam;
53 | }
54 |
55 | /**
56 | * Check if renavam has correct length.
57 | *
58 | * @param string $renavam
59 | * @return bool
60 | */
61 | protected function renavamHasCorrectLength(string $renavam): bool
62 | {
63 | return !!preg_match("/[0-9]{11}/", $renavam);
64 | }
65 |
66 | /**
67 | * Get the real last digit calculated.
68 | *
69 | * @param string $renavam
70 | * @return int
71 | */
72 | private function getRealLastDigit(string $renavam): int
73 | {
74 | $renavamReverseWithoutDigit = $this->sanitizeToReverseWithoutDigit($renavam);
75 | $sum = $this->calcSumByRenavamReverseWithoutDigit($renavamReverseWithoutDigit);
76 |
77 | $mod11 = $sum % self::RENAVAM_SIZE;
78 | $lastDigitCalculated = self::RENAVAM_SIZE - $mod11;
79 |
80 | return $lastDigitCalculated >= 10 ? 0 : $lastDigitCalculated;
81 | }
82 |
83 | /**
84 | * Sanitize the renavam to without digit.
85 | *
86 | * @param string $renavam
87 | * @return string
88 | */
89 | protected function sanitizeToReverseWithoutDigit(string $renavam): string
90 | {
91 | $renavamWithoutDigit = substr($renavam, 0, 10);
92 |
93 | return strrev($renavamWithoutDigit);
94 | }
95 |
96 | /**
97 | * Calculate the sum value by renavam reverse without digit.
98 | *
99 | * @param string $renavamReverseWithoutDigit
100 | * @return int
101 | */
102 | protected function calcSumByRenavamReverseWithoutDigit(string $renavamReverseWithoutDigit): int
103 | {
104 | $sum = 0;
105 |
106 | for ($i = 0; $i < 8; $i++) {
107 | $numeral = (int) substr($renavamReverseWithoutDigit, $i, 1);
108 | $multiplier = $i + 2;
109 | $sum += $numeral * $multiplier;
110 | }
111 |
112 | $sum += $renavamReverseWithoutDigit[8] * 2;
113 | $sum += $renavamReverseWithoutDigit[9] * 3;
114 |
115 | return $sum;
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/validator-docs/Rules/Sanitization.php:
--------------------------------------------------------------------------------
1 | sanitize($value);
16 |
17 | $uf = substr($input, -4, 2);
18 |
19 | if (
20 | ((mb_strlen($input) < 5) || (mb_strlen($input) > 13)) ||
21 | (str_repeat($input[1], mb_strlen($input)) == $input) ||
22 | ($uf < 1 || $uf > 28)
23 | ) {
24 | return false;
25 | }
26 |
27 | $dv = substr($input, -2);
28 | $base = 2;
29 |
30 | $sequencia = substr($input, 0, -4);
31 |
32 | for ($i = 0; $i < 2; $i++) {
33 | $fator = 9;
34 | $soma = 0;
35 |
36 | for ($j = (mb_strlen($sequencia) - 1); $j > -1; $j--) {
37 | $soma += $sequencia[$j] * $fator;
38 |
39 | if ($fator == $base) {
40 | $fator = 10;
41 | }
42 |
43 | $fator--;
44 | }
45 |
46 | $digito = $soma % 11;
47 |
48 | if (($digito == 0) and ($uf < 3)) {
49 | $digito = 1;
50 | } elseif ($digito == 10) {
51 | $digito = 0;
52 | }
53 |
54 | if ($dv[$i] != $digito) {
55 | return false;
56 | }
57 |
58 | switch ($i) {
59 | case '0':
60 | $sequencia = $uf . $digito;
61 | break;
62 | }
63 | }
64 |
65 | return true;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/validator-docs/Validator.php:
--------------------------------------------------------------------------------
1 | execute($value, $document);
37 | }
38 | }
39 |
40 | protected function validateCpf($attribute, $value): bool
41 | {
42 | $cpf = new Cpf();
43 |
44 | $this->validateFormat($value, 'cpf');
45 |
46 | return $cpf->validateCpf($attribute, $value);
47 | }
48 |
49 | protected function validateCnpj($attribute, $value): bool
50 | {
51 | $cnpj = new Cnpj();
52 |
53 | return $cnpj->validateCnpj($attribute, $value);
54 | }
55 |
56 | protected function validateCpfCnpj($attribute, $value): bool
57 | {
58 | $cpf = new Cpf();
59 | $cnpj = new Cnpj();
60 |
61 | return ($cpf->validateCpf($attribute, $value) || $cnpj->validateCnpj($attribute, $value));
62 | }
63 |
64 | protected function validateCnh($attribute, $value): bool
65 | {
66 | $cnh = new Cnh();
67 |
68 | return $cnh->validateCnh($attribute, $value);
69 | }
70 |
71 | protected function validateTituloEleitor($attribute, $value): bool
72 | {
73 | $tituloEleitoral = new TituloEleitoral();
74 |
75 | return $tituloEleitoral->validateTituloEleitor($attribute, $value);
76 | }
77 |
78 | protected function validateNis($attribute, $value): bool
79 | {
80 | $nis = new Nis();
81 |
82 | return $nis->validateNis($attribute, $value);
83 | }
84 |
85 | protected function validateCns($attribute, $value): bool
86 | {
87 | $cns = new Cns();
88 |
89 | return $cns->validateCns($attribute, $value);
90 | }
91 |
92 | protected function validateCertidao($attribute, $value): bool
93 | {
94 | $certidao = new Certidao();
95 |
96 | return $certidao->validateCertidao($attribute, $value);
97 | }
98 |
99 | protected function validateInscricaoEstadual($attribute, $value, $parameters): bool
100 | {
101 | $inscricaoEstadual = new InscricaoEstadual();
102 |
103 | return $inscricaoEstadual->validateInscricaoEstadual($attribute, $value, $parameters);
104 | }
105 |
106 | protected function validateRenavam($attribute, $value): bool
107 | {
108 | $renavam = new Renavam();
109 |
110 | return $renavam->validateRenavam($attribute, $value);
111 | }
112 |
113 | protected function validatePlaca($attribute, $value): bool
114 | {
115 | $placa = new Placa();
116 |
117 | return $placa->validatePlaca($attribute, $value);
118 | }
119 |
120 | protected function validateDdd($attribute, $value): bool
121 | {
122 | $ddd = new Ddd();
123 |
124 | return $ddd->validateDdd($attribute, $value);
125 | }
126 |
127 | protected function validatePassaporte($attribute, $value): bool
128 | {
129 | $passaporte = new Passaporte();
130 | return $passaporte->validatePassaporte($attribute, $value);
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/src/validator-docs/ValidatorFormats.php:
--------------------------------------------------------------------------------
1 | app['validator']
28 | ->resolver(
29 | function ($translator, $data, $rules, $messages, $attributes) use ($me, $validatorFormats) {
30 | $messages += $me->getMessages();
31 |
32 | return new Validator($translator, $validatorFormats, $data, $rules, $messages, $attributes);
33 | }
34 | );
35 | }
36 |
37 | protected function getMessages()
38 | {
39 | return [
40 | 'cnh' => 'Carteira Nacional de Habilitação inválida',
41 | 'titulo_eleitor' => 'Título de Eleitor inválido',
42 | 'cnpj' => 'CNPJ inválido',
43 | 'cpf' => 'CPF inválido',
44 | 'renavam' => 'Renavam inválido',
45 | 'cpf_cnpj' => 'CPF ou CNPJ inválido',
46 | 'nis' => 'PIS/PASEP/NIT/NIS inválido',
47 | 'cns' => 'Cartão Nacional de Saúde inválido',
48 | 'inscricao_estadual' => 'Inscrição Estadual ou UF inválidas',
49 | 'certidao' => 'Número da Certidão inválido',
50 | 'ddd' => 'DDD inválido',
51 | 'placa' => 'Placa inválida',
52 | 'passaporte' => 'Passaporte inválido',
53 | 'formato_cnpj' => 'Formato inválido para CNPJ',
54 | 'formato_cpf' => 'Formato inválido para CPF',
55 | 'formato_cpf_cnpj' => 'Formato inválido para CPF ou CNPJ',
56 | 'formato_nis' => 'Formato inválido para PIS/PASEP/NIT/NIS',
57 | 'formato_certidao' => 'Formato inválido para Certidão',
58 | ];
59 | }
60 |
61 | /**
62 | * Register the service provider.
63 | *
64 | * @return void
65 | */
66 | public function register()
67 | {
68 | }
69 |
70 | /**
71 | * Get the services provided by the provider.
72 | *
73 | * @return array
74 | */
75 | public function provides()
76 | {
77 | return [];
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/tests/Rules/RenavamTest.php:
--------------------------------------------------------------------------------
1 | validateRenavam('', $renavam);
20 |
21 | $this->assertSame($esperado, $atual, $renavam);
22 | }
23 |
24 | public function renavamProvider(): array
25 | {
26 | $correctValues = [32094074362, 23478829239, 34145742746, 41833820181, 63988496222];
27 | $wrongValues = [11111111111, 32094074212, 62128843267];
28 |
29 | return array_reduce(
30 | array_merge($correctValues, $wrongValues),
31 | function ($acc, $value) use ($correctValues) {
32 | $key = "Renavam " . $value;
33 | $testProperties = ['renavam' => $value, 'esperado' => in_array($value, $correctValues)];
34 |
35 | $acc[$key] = $testProperties;
36 | return $acc;
37 | },
38 | []
39 | );
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/tests/SanitizationTestCase.php:
--------------------------------------------------------------------------------
1 | getMockForAbstractClass(Sanitization::class);
13 | $this->assertEquals("", $mock->sanitize(null));
14 | }
15 |
16 | /** @test **/
17 | public function sanitizeRetornaSomenteDigitos()
18 | {
19 | $mock = $this->getMockForAbstractClass(Sanitization::class);
20 | $this->assertEquals("53084587000120", $mock->sanitize('a53.084.587/0001-20z'));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tests/TestValidator.php:
--------------------------------------------------------------------------------
1 | '094.050.986-59'],
14 | ['certo' => 'cpf']
15 | );
16 |
17 | $incorrect = Validator::make(
18 | ['errado' => '99800-1926'],
19 | ['errado' => 'cpf']
20 | );
21 |
22 | $this->assertTrue($correct->passes());
23 |
24 | $this->assertTrue($incorrect->fails());
25 | }
26 |
27 | /** @test **/
28 | public function cnpj()
29 | {
30 | $correct = Validator::make(
31 | ['certo' => '53.084.587/0001-20'],
32 | ['certo' => 'cnpj']
33 | );
34 |
35 | $incorrect = Validator::make(
36 | ['errado' => '51.084.587/0001-20'],
37 | ['errado' => 'cnpj']
38 | );
39 |
40 | $this->assertTrue($correct->passes());
41 |
42 | $this->assertTrue($incorrect->fails());
43 | }
44 |
45 | /** @test **/
46 | public function cpfECnpjNoMesmoAtributo()
47 | {
48 | $correct = Validator::make(
49 | ['certo' => '53.084.587/0001-20'],
50 | ['certo' => 'cpf-cnpj']
51 | );
52 |
53 | $incorrect = Validator::make(
54 | ['errado' => '99800-1926'],
55 | ['errado' => 'cpf-cnpj']
56 | );
57 |
58 | $this->assertTrue($correct->passes());
59 |
60 | $this->assertTrue($incorrect->fails());
61 | }
62 |
63 | /** @test **/
64 | public function cnh()
65 | {
66 | $correct = Validator::make(
67 | ['certo' => '96784547943'],
68 | ['certo' => 'cnh']
69 | );
70 |
71 | $incorrect = Validator::make(
72 | ['errado' => '96784547999'],
73 | ['errado' => 'cnh']
74 | );
75 |
76 | $this->assertTrue($correct->passes());
77 |
78 | $this->assertTrue($incorrect->fails());
79 |
80 | $correct = Validator::make(
81 | ['certo' => '04463004100'],
82 | ['certo' => 'cnh']
83 | );
84 |
85 | $this->assertTrue($correct->passes());
86 | }
87 |
88 | /** @test **/
89 | public function tituloEleitoral()
90 | {
91 | $correct = Validator::make(
92 | ['certo' => '3021260'],
93 | ['certo' => 'titulo_eleitor']
94 | );
95 |
96 | $incorrect = Validator::make(
97 | ['errado' => '1000101230190'],
98 | ['errado' => 'titulo_eleitor']
99 | );
100 |
101 | $this->assertTrue($correct->passes());
102 |
103 | $this->assertTrue($incorrect->fails());
104 | }
105 |
106 | /** @test **/
107 | public function nis()
108 | {
109 | $correct = Validator::make(
110 | ['certo' => '201.73374.34-9'],
111 | ['certo' => 'nis']
112 | );
113 |
114 | $incorrect = Validator::make(
115 | ['errado' => '201.73374.34-0'],
116 | ['errado' => 'nis']
117 | );
118 |
119 | $this->assertTrue($correct->passes());
120 |
121 | $this->assertTrue($incorrect->fails());
122 | }
123 |
124 | /** @test **/
125 | public function cns()
126 | {
127 | // Definitiva
128 | $correct = Validator::make(
129 | ['certo' => '116 3876 9194 0009'],
130 | ['certo' => 'cns']
131 | );
132 |
133 | $incorrect = Validator::make(
134 | ['errado' => '116 5698 9194 0009'],
135 | ['errado' => 'cns']
136 | );
137 |
138 | $this->assertTrue($correct->passes());
139 | $this->assertTrue($incorrect->fails());
140 |
141 | // Provisória
142 | $correct = Validator::make(
143 | ['certo' => '892 1623 5477 0008'],
144 | ['certo' => 'cns']
145 | );
146 |
147 | $incorrect = Validator::make(
148 | ['errado' => '892 2641 5477 0008'],
149 | ['errado' => 'cns']
150 | );
151 |
152 | $this->assertTrue($correct->passes());
153 | $this->assertTrue($incorrect->fails());
154 | }
155 |
156 | /** @test **/
157 | public function certidao()
158 | {
159 | $correct = Validator::make(
160 | ['certo' => '659447 02 55 9015 1 99679 468 2559590-16'],
161 | ['certo' => 'certidao']
162 | );
163 |
164 | $incorrect = Validator::make(
165 | ['errado' => '659447 02 55 2015 1 27861 468 2559590-32'],
166 | ['errado' => 'certidao']
167 | );
168 |
169 | $this->assertTrue($correct->passes());
170 | $this->assertTrue($incorrect->fails());
171 | }
172 |
173 | public function inscricoesEstaduais()
174 | {
175 | $inscricoesEstaduaisValidas = [
176 | "AC" => "0184765932153",
177 | "AL" => "248308335",
178 | "AP" => "039895661",
179 | "AM" => "292278012",
180 | "BA" => "96338555",
181 | "CE" => "980874165",
182 | "DF" => "0740769300107",
183 | "ES" => "342048090",
184 | "GO" => "107900459",
185 | "MA" => "122917510",
186 | "MT" => "55160385510",
187 | "MS" => "283814659",
188 | "MG" => "0526366324132",
189 | "PA" => "158330005",
190 | "PB" => "439622301",
191 | "PR" => "5714953410",
192 | "PE" => "920145698",
193 | "PI" => "758505183",
194 | "RJ" => "61804315",
195 | "RN" => "208627715",
196 | "RS" => "3821957672",
197 | "RO" => "52059985926850",
198 | "RR" => "249977060",
199 | "SC" => "696192667",
200 | "SP" => "653172024009",
201 | "SE" => "646597361",
202 | "TO" => "75036274184",
203 | ];
204 |
205 | foreach ($inscricoesEstaduaisValidas as $siglaUf => $inscricaoEstadual) {
206 | $inscricoesEstaduaisValidas[$siglaUf] = [
207 | 'data' => $inscricaoEstadual,
208 | 'rules' => "inscricao_estadual:$siglaUf",
209 | 'assert' => 'passes'
210 | ];
211 | }
212 |
213 | return $inscricoesEstaduaisValidas + [
214 | // válidas
215 | 'válida sem formatação' => [
216 | 'data' => '82679341',
217 | 'rules' => 'inscricao_estadual:BA',
218 | 'assert' => 'passes'
219 | ],
220 | 'válida com estado (UF) em letras minúsculas' => [
221 | 'data' => '82679341',
222 | 'rules' => 'inscricao_estadual:ba',
223 | 'assert' => 'passes'
224 | ],
225 | 'válida com formatação' => [
226 | 'data' => '826793-41',
227 | 'rules' => 'inscricao_estadual:BA',
228 | 'assert' => 'passes'
229 | ],
230 | 'válida com formatação qualquer não-numérica' => [
231 | 'data' => '8 2__6-7*9.3/41',
232 | 'rules' => 'inscricao_estadual:BA',
233 | 'assert' => 'passes'
234 | ],
235 |
236 | // inválidas
237 | 'inválida cálculo errado' => [
238 | 'data' => '82679342', // último digito deveria ser 1
239 | 'rules' => 'inscricao_estadual:BA',
240 | 'assert' => 'fails'
241 | ],
242 | 'inválida se estado (UF) errado' => [
243 | 'data' => '82679341',
244 | 'rules' => 'inscricao_estadual:SP', // deveria ser BA
245 | 'assert' => 'fails'
246 | ],
247 | 'inválida se estado (UF) inexistente' => [
248 | 'data' => '82679341',
249 | 'rules' => 'inscricao_estadual:ZA',
250 | 'assert' => 'fails'
251 | ],
252 | 'inválida se estado (UF) invalido (maior)' => [
253 | 'data' => '82679341',
254 | 'rules' => 'inscricao_estadual:askdjahsd',
255 | 'assert' => 'fails'
256 | ],
257 | 'inválida se estado (UF) invalido (menor)' => [
258 | 'data' => '82679341',
259 | 'rules' => 'inscricao_estadual:y',
260 | 'assert' => 'fails'
261 | ],
262 | 'inválida se estado (UF) invalido (numerico)' => [
263 | 'data' => '82679341',
264 | 'rules' => 'inscricao_estadual:12',
265 | 'assert' => 'fails'
266 | ],
267 | 'inválida se estado (UF) não informado' => [
268 | 'data' => '82679341',
269 | 'rules' => 'inscricao_estadual',
270 | 'assert' => 'fails'
271 | ],
272 | ];
273 | }
274 |
275 | /**
276 | * @test
277 | * @dataProvider inscricoesEstaduais
278 | * @param $data
279 | * @param $rules
280 | * @param $assert
281 | */
282 | public function inscricaoEstadual($data, $rules, $assert)
283 | {
284 | $correct = Validator::make(
285 | ['input_inscricao_estadual' => $data],
286 | ['input_inscricao_estadual' => $rules]
287 | );
288 | $this->assertTrue($correct->{$assert}());
289 | }
290 |
291 | /** @test **/
292 | public function placa()
293 | {
294 | $correct = Validator::make(
295 | ['certo' => 'P15186'],
296 | ['certo' => 'placa']
297 | );
298 |
299 | $incorrect = Validator::make(
300 | ['errado' => 'X1234'],
301 | ['errado' => 'placa']
302 | );
303 |
304 | $this->assertTrue($correct->passes());
305 |
306 | $this->assertTrue($incorrect->fails());
307 | }
308 |
309 | /**
310 | * @test
311 | */
312 | public function ddd()
313 | {
314 | $dddExisting = array_merge(
315 | range(11, 19),
316 | [21, 22, 24, 27, 28],
317 | range(31, 35),
318 | [37, 38],
319 | range(41, 49),
320 | [51],
321 | range(53, 55),
322 | range(61, 69),
323 | [71],
324 | range(73, 75),
325 | [77, 79],
326 | range(81, 89),
327 | range(91, 99)
328 | );
329 |
330 | $correct = Validator::make(
331 | ['certo' => $dddExisting[array_rand($dddExisting)]],
332 | ['certo' => 'ddd']
333 | );
334 |
335 | $incorrect = Validator::make(
336 | ['errado' => '10'],
337 | ['errado' => 'ddd']
338 | );
339 |
340 | $this->assertTrue($correct->passes());
341 |
342 | $this->assertTrue($incorrect->fails());
343 | }
344 |
345 | /** @test **/
346 | public function passaporte()
347 | {
348 | $correct = Validator::make(
349 | ['certo' => 'GB139485'],
350 | ['certo' => 'passaporte']
351 | );
352 |
353 | $incorrect = Validator::make(
354 | ['errado' => 'A3948'],
355 | ['errado' => 'passaporte']
356 | );
357 |
358 | $this->assertTrue($correct->passes());
359 | $this->assertTrue($incorrect->fails());
360 | }
361 | }
362 |
--------------------------------------------------------------------------------
/tests/ValidatorFormatsTest.php:
--------------------------------------------------------------------------------
1 | validatorFormats = new ValidatorFormats();
16 | }
17 |
18 | /** @test */
19 | public function lancaExcecaoQuandoValorNaoExiste(): void
20 | {
21 | $this->expectException(Exception::class);
22 | $this->expectExceptionMessage('Value not informed.');
23 |
24 | $this->validatorFormats->execute('', 'cpf');
25 | }
26 |
27 | /** @test */
28 | public function lancaExcecaoQuandoDocumentoNaoSuportado(): void
29 | {
30 | $this->expectException(Exception::class);
31 | $this->expectExceptionMessage('Don\'t exists validator for this document.');
32 |
33 | $this->validatorFormats->execute('053.222.333-74', 'foo');
34 | }
35 |
36 | /** @test */
37 | public function formatoCpf(): void
38 | {
39 | self::assertTrue($this->validatorFormats->execute('000.000.000-00', 'cpf'));
40 | self::assertFalse($this->validatorFormats->execute('00000000000', 'cpf'));
41 | }
42 |
43 | /** @test */
44 | public function formatoCnpj(): void
45 | {
46 | self::assertTrue($this->validatorFormats->execute('00.000.000/0000-00', 'cnpj'));
47 | self::assertFalse($this->validatorFormats->execute('00000000000000', 'cnpj'));
48 | }
49 |
50 | /** @test */
51 | public function formatoCertidao(): void
52 | {
53 | self::assertTrue($this->validatorFormats->execute('434546.02.55.2019.1.71037.134.6484858-10', 'certidao'));
54 | self::assertFalse($this->validatorFormats->execute('434546.02.55.2019.1.71037.134.6484858', 'certidao'));
55 | }
56 |
57 | /** @test */
58 | public function formatoNis(): void
59 | {
60 | self::assertTrue($this->validatorFormats->execute('201.73374.34-9', 'nis'));
61 | }
62 |
63 | /** @test */
64 | public function formatocpfECnpjNoMesmoAtributo(): void
65 | {
66 | self::assertTrue($this->validatorFormats->execute('111.111.111-11', 'cpfCnpj'));
67 | self::assertTrue($this->validatorFormats->execute('63.657.343/0001-43', 'CpfCnpj'));
68 | self::assertFalse($this->validatorFormats->execute('11111111111', 'CpfCnpj'));
69 | self::assertFalse($this->validatorFormats->execute('63.657.343/0001', 'CpfCnpj'));
70 | }
71 |
72 | /** @test */
73 | public function formatoRenavam()
74 | {
75 | $correct = Validator::make(
76 | ['certo' => '197073212'],
77 | ['certo' => 'renavam']
78 | );
79 |
80 | $incorrect = Validator::make(
81 | ['errado' => '1234555582'],
82 | ['errado' => 'renavam']
83 | );
84 |
85 | $this->assertTrue($correct->passes());
86 | $this->assertTrue($incorrect->fails());
87 |
88 | $correct = Validator::make(
89 | ['certo' => '1970.73212'],
90 | ['certo' => 'renavam']
91 | );
92 |
93 | $this->assertTrue($correct->passes());
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/tests/ValidatorTestCase.php:
--------------------------------------------------------------------------------
1 | app->register(ValidatorProvider::class);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------