├── .github
└── workflows
│ └── php.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml
├── src
└── pt-br-validator
│ ├── Rules
│ ├── Celular.php
│ ├── CelularComCodigo.php
│ ├── CelularComCodigoSemMascara.php
│ ├── CelularComDdd.php
│ ├── Cnh.php
│ ├── Cnpj.php
│ ├── Cns.php
│ ├── Cpf.php
│ ├── CpfOuCnpj.php
│ ├── FormatoCep.php
│ ├── FormatoCnpj.php
│ ├── FormatoCpf.php
│ ├── FormatoCpfOuCnpj.php
│ ├── FormatoPis.php
│ ├── FormatoPlacaDeVeiculo.php
│ ├── Pis.php
│ ├── Telefone.php
│ ├── TelefoneComCodigo.php
│ ├── TelefoneComDdd.php
│ └── Uf.php
│ └── ValidatorProvider.php
└── tests
├── .gitkeep
├── Unit
├── TestRules.php
└── TestValidator.php
├── ValidatorTestCase.php
└── coverage
└── .gitignore
/.github/workflows/php.yml:
--------------------------------------------------------------------------------
1 | name: PHP Composer
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | - dev
8 | pull_request:
9 | branches:
10 | - master
11 |
12 | jobs:
13 | build:
14 | runs-on: ${{ matrix.operating-system }}
15 |
16 | strategy:
17 | matrix:
18 | operating-system: [ubuntu-latest]
19 | php-versions: ['7.2', '7.3', '7.4', '8.0', '8.2', '8.3', '8.4']
20 |
21 | steps:
22 | - uses: actions/checkout@v2
23 |
24 | - name: Validate composer.json and composer.lock
25 | run: composer validate --strict
26 |
27 | - name: Cache Composer packages
28 | id: composer-cache
29 | uses: actions/cache@v2
30 | with:
31 | path: vendor
32 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
33 | restore-keys: |
34 | ${{ runner.os }}-php-
35 |
36 | - name: Install dependencies
37 | run: composer install --prefer-dist --no-progress
38 |
39 | - name: Run test suite
40 | run: composer test
41 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor
2 | composer.phar
3 | composer.lock
4 | .DS_Store
5 | pt-br-validator.sublime-project
6 | pt-br-validator.sublime-workspace
7 | /.phpintel/
8 | .phpunit.cache/
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: php
2 | dist: trusty
3 |
4 | php:
5 | - 7.2
6 | - 7.3
7 | - 7.4
8 | - 8.0
9 | - 8.1
10 |
11 | before_script:
12 | - travis_retry composer self-update
13 | - travis_retry composer install --prefer-source --no-interaction
14 |
15 | script: ./vendor/bin/phpunit
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 phplegends
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 | # pt-br-validator: Validações brasileiras para Laravel.
2 |
3 | Esta biblioteca adiciona validações brasileira ao Laravel, como CPF, CNPJ, Placa de Carro, CEP, Telefone, Celular e afins.
4 |
5 | :brazil::brazil::brazil:
6 |
7 | ## Versões
8 |
9 |
10 |
11 | Laravel |
12 | Biblioteca |
13 |
14 |
15 | 4.* |
16 | 4.* |
17 |
18 |
19 | 5.* |
20 | 5.1.* |
21 |
22 |
23 | ^6.0 || ^7.0 || ^8.0 |
24 | ^8.0 |
25 |
26 |
27 | ^9.0 |
28 | ^9.0 |
29 |
30 |
31 | ^10.0 |
32 | ^10.0 |
33 |
34 |
35 | ^11.0 |
36 | ^11.0 |
37 |
38 |
39 | ^12.0 |
40 | ^12.0 |
41 |
42 |
43 |
44 | ## Instalação
45 |
46 | Navegue até a pasta do seu projeto, por exemplo:
47 |
48 | ```
49 | cd /etc/www/projeto
50 | ```
51 |
52 | E então execute:
53 |
54 | ```
55 | composer require laravellegends/pt-br-validator
56 | ```
57 |
58 | Caso esteja utilizando uma versão desta biblioteca anterior a `5.2`, você deve o provider em `config/app.php`
59 | ```php
60 | 'providers' => [
61 | // ... outros pacotes
62 | LaravelLegends\PtBrValidator\ValidatorProvider::class
63 | ]
64 | ```
65 | Agora, para utilizar a validação, basta fazer o procedimento padrão do `Laravel`.
66 |
67 | A diferença é que será possível usar os seguintes métodos de validação:
68 |
69 | | REGRA | Descrição |
70 | |:-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------:|
71 | | Celular | Valida se o campo está no formato (**`99999-9999`** ou **`9999-9999`**) |
72 | | celular_com_ddd | Valida se o campo está no formato (**`(99)99999-9999`** ou **`(99)9999-9999`** ou **`(99) 99999-9999`** ou **`(99) 9999-9999`**) |
73 | | celular_com_codigo | Valida se o campo está no formato `+99(99)99999-9999` ou +99(99)9999-9999. |
74 | | cnpj | Valida se o campo é um CNPJ válido. É possível gerar um CNPJ válido para seus testes utilizando o site [geradorcnpj.com](http://www.geradorcnpj.com/) |
75 | | cpf | Valida se o campo é um CPF válido. É possível gerar um CPF válido para seus testes utilizando o site [geradordecpf.org](http://geradordecpf.org) |
76 | | cns | Valida se o campo é um CNS válido. Use o site [geradornv.com.br](https://geradornv.com.br/gerador-cns/) para testar |
77 | | formato_cnpj | Valida se o campo tem uma máscara de CNPJ correta (**`99.999.999/9999-99`**). |
78 | | formato_cpf | Valida se o campo tem uma máscara de CPF correta (**`999.999.999-99`**). |
79 | | formato_cep | Valida se o campo tem uma máscara de correta (**`99999-999`** ou **`99.999-999`**). |
80 | | telefone | Valida se o campo tem umas máscara de telefone (**`9999-9999`**). |
81 | | telefone_com_ddd | Valida se o campo tem umas máscara de telefone com DDD (**`(99)9999-9999`**). |
82 | | telefone_com_codigo | Valida se o campo tem umas máscara de telefone com DDD (**`+55(99)9999-9999`**). |
83 | | formato_placa_de_veiculo | Valida se o campo tem o formato válido de uma placa de veículo (incluindo o padrão MERCOSUL). |
84 | | formato_pis | Valida se o campo tem o formato de PIS. |
85 | | pis | Valida se o PIS é válido. |
86 | | cpf_ou_cnpj | Valida se o campo é um CPF ou CNPJ |
87 | | formato_cpf_ou_cnpj | Valida se o campo contém um formato de CPF ou CNPJ |
88 | | uf | Valida se o campo contém uma sigla de Estado válido (UF) |
89 |
90 | ## Testando as validações do PtBrValidator
91 |
92 | Com isso, é possível fazer um teste simples
93 |
94 | ```php
95 |
96 | $validator = \Validator::make(
97 | ['telefone' => '(77)9999-3333'],
98 | ['telefone' => 'required|telefone_com_ddd']
99 | );
100 |
101 | dd($validator->fails());
102 |
103 | ```
104 |
105 | Você pode utilizá-lo também com a instância de `Illuminate\Http\Request`, através do método `validate`.
106 |
107 | Veja:
108 |
109 | ```php
110 |
111 | use Illuminate\Http\Request;
112 |
113 | // URL: /testando?telefone=3455-1222
114 |
115 | Route::get('testando', function (Request $request) {
116 |
117 | try{
118 |
119 | $dados = $request->validate([
120 | 'telefone' => 'required|telefone',
121 | // outras validações aqui
122 | ]);
123 |
124 | } catch (\Illuminate\Validation\ValidationException $e) {
125 | dd($e->errors());
126 | }
127 |
128 | });
129 |
130 | ```
131 |
132 | ### Customizando as mensagens
133 |
134 | Todas as validações citadas acima já contam mensagens padrões de validação, porém, é possível alterar isto usando o terceiro parâmetro de `Validator::make`. Este parâmetro deve ser um array onde os índices sejam os nomes das validações e os valores devem ser as respectivas mensagens.
135 |
136 | Por exemplo:
137 |
138 | ```php
139 | Validator::make($valor, $regras, ['celular_com_ddd' => 'O campo :attribute não é um celular'])
140 | ```
141 |
142 | Ou através do método `messages` do seu Request criado pelo comando `php artisan make:request`.
143 |
144 | ```php
145 | public function messages() {
146 |
147 | return [
148 | 'campo.telefone' => 'Telefone não válido!'
149 | ];
150 | }
151 | ```
152 |
153 | ### Acessando as Regras separadamente
154 |
155 | Caso tenha necessidade de acessar alguma regra separadamente, você poderá ter acesso as seguintes classes:
156 |
157 | ```
158 | \LaravelLegends\PtBrValidator\Rules\Celular::class
159 | \LaravelLegends\PtBrValidator\Rules\CelularComDdd::class
160 | \LaravelLegends\PtBrValidator\Rules\CelularComCodigo::class
161 | \LaravelLegends\PtBrValidator\Rules\Cnh::class
162 | \LaravelLegends\PtBrValidator\Rules\Cnpj::class
163 | \LaravelLegends\PtBrValidator\Rules\Cpf::class
164 | \LaravelLegends\PtBrValidator\Rules\Cns::class
165 | \LaravelLegends\PtBrValidator\Rules\FormatoCnpj::class
166 | \LaravelLegends\PtBrValidator\Rules\FormatoCpf::class
167 | \LaravelLegends\PtBrValidator\Rules\Telefone::class
168 | \LaravelLegends\PtBrValidator\Rules\TelefoneComDdd::class
169 | \LaravelLegends\PtBrValidator\Rules\TelefoneComCodigo::class
170 | \LaravelLegends\PtBrValidator\Rules\FormatoCep::class
171 | \LaravelLegends\PtBrValidator\Rules\FormatoPlacaDeVeiculo::class
172 | \LaravelLegends\PtBrValidator\Rules\FormatoPis::class
173 | \LaravelLegends\PtBrValidator\Rules\Pis::class
174 | \LaravelLegends\PtBrValidator\Rules\CpfOuCnpj::class
175 | \LaravelLegends\PtBrValidator\Rules\FormatoCpfOuCnpj::class
176 | \LaravelLegends\PtBrValidator\Rules\Uf::class
177 | ```
178 |
179 | Por exemplo, se você deseja validar o formato do campo de um CPF, você pode utilizar a classe `LaravelLegends\PtBrValidator\Rules\FormatoCpf` da seguinte forma:
180 |
181 | ```php
182 | use Illuminate\Http\Request;
183 | use LaravelLegends\PtBrValidator\Rules\FormatoCpf;
184 |
185 | // testando?cpf=valor_invalido
186 |
187 | Route::get('testando', function (Request $request) {
188 |
189 | try{
190 |
191 | $dados = $request->validate([
192 | 'cpf' => ['required', new FormatoCpf]
193 | // outras validações aqui
194 | ]);
195 |
196 | } catch (\Illuminate\Validation\ValidationException $e) {
197 | dd($e->errors());
198 | }
199 |
200 | });
201 | ```
202 |
203 | ## Changelog
204 |
205 | - 9.1.0 - Validação `cns` (cartão nacional de saúde) adicionada.
206 | - 8.0.3 - Validação `uf` adicionada.
207 | - 8.0.2 - Validação `cpf_ou_cnpj`
208 | - 5.2.1 - Validação `cpf_ou_cnpj`
209 |
210 |
211 |
212 |
213 | ## Sugestões
214 |
215 | [Eloquent Filter](https://github.com/LaravelLegends/eloquent-filter): Essa biblioteca foi desenvolvida com o propósito de criar facilmente filtros de pesquisa para APIs REST. Com esta biblioteca, você vai economizar várias linhas de códigos, bem como manter um padrão global para filtros de pesquisa em sua aplicação escrita em Laravel.
216 |
217 |
218 | ## Doações
219 |
220 | [Paypal](https://www.paypal.com/donate/?business=KCAGBVD5TJLUL&no_recurring=0&item_name=Ajude+a+sustentar+algu%C3%A9m+que+apoia+o+open-source+%3A%29¤cy_code=BRL)
221 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "laravellegends/pt-br-validator",
3 | "description": "Uma biblioteca contendo validações de formatos Brasileiros, para o Laravel",
4 | "license": "MIT",
5 | "authors": [
6 | {
7 | "name": "Wallace de Souza Vizerra",
8 | "email": "wallacemaxters@gmail.com"
9 | }
10 | ],
11 | "require": {
12 | "illuminate/support": "^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0 || ^12.0"
13 | },
14 | "autoload": {
15 | "psr-4": {
16 | "LaravelLegends\\PtBrValidator\\": "src/pt-br-validator"
17 | }
18 | },
19 | "extra": {
20 | "laravel": {
21 | "providers": [
22 | "LaravelLegends\\PtBrValidator\\ValidatorProvider"
23 | ]
24 | }
25 | },
26 | "minimum-stability": "stable",
27 | "require-dev": {
28 | "orchestra/testbench": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^10.0",
29 | "phpunit/phpunit": "^8.3 || ^9.0 || ^11.5.3"
30 | },
31 | "scripts": {
32 | "test": "./vendor/bin/phpunit"
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
16 | ./tests/Unit
17 |
18 |
19 |
20 |
22 |
23 | src
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Celular.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class Celular implements Rule
11 | {
12 |
13 | /**
14 | * Valida o formato do celular
15 | * @param string $attribute
16 | * @param string $value
17 | * @return boolean
18 | */
19 | public function passes($attribute, $value)
20 | {
21 | return preg_match('/^\d{4,5}-\d{4}$/', $value) > 0;
22 | }
23 |
24 |
25 | public function message()
26 | {
27 | return 'O campo :attribute não é um celular válido.';
28 | }
29 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/CelularComCodigo.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class CelularComCodigo implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida o formato do celular com código do país
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 | public function passes($attribute, $value)
22 | {
23 | return preg_match('/^[+]\d{1,2}\s?\(\d{2}\)\s?\d{4,5}\-\d{4}$/', $value) > 0;
24 | }
25 |
26 | public function message()
27 | {
28 | return 'O campo :attribute não é um celular com DDD válido.';
29 | }
30 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/CelularComCodigoSemMascara.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class CelularComCodigoSemMascara implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida o formato do celular com código do país
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 | public function passes($attribute, $value)
22 | {
23 | return preg_match('/^[+]\d{1,2}\s?\d{2}\s?\d{4,5}\d{4}$/', $value) > 0;
24 | }
25 |
26 | public function message()
27 | {
28 | return 'O campo :attribute não é um celular válido. Exemplo de celular válido +5514999999999';
29 | }
30 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/CelularComDdd.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class CelularComDdd implements Rule
11 | {
12 | /**
13 | * Valida o formato do celular junto com o ddd
14 | *
15 | * @param string $attribute
16 | * @param string $value
17 | * @return boolean
18 | */
19 | public function passes($attribute, $value)
20 | {
21 | return preg_match('/^\(\d{2}\)\s?\d{4,5}-\d{4}$/', $value) > 0;
22 | }
23 |
24 | public function message()
25 | {
26 | return 'O campo :attribute não é um celular com DDD válido.';
27 | }
28 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Cnh.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class Cnh implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida se o CNH é válido
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 |
22 | public function passes($attribute, $value)
23 | {
24 | $ret = false;
25 |
26 | if ((strlen($input = preg_replace('/[^\d]/', '', $value)) == 11)
27 | && (str_repeat($input[1], 11) != $input)) {
28 | $dsc = 0;
29 |
30 | for ($i = 0, $j = 9, $v = 0; $i < 9; ++$i, --$j) {
31 |
32 | $v += (int) $input[$i] * $j;
33 |
34 | }
35 |
36 | if (($vl1 = $v % 11) >= 10) {
37 |
38 | $vl1 = 0;
39 | $dsc = 2;
40 |
41 | }
42 |
43 | for ($i = 0, $j = 1, $v = 0; $i < 9; ++$i, ++$j) {
44 |
45 | $v += (int) $input[$i] * $j;
46 |
47 | }
48 |
49 | $vl2 = ($x = ($v % 11)) >= 10 ? 0 : $x - $dsc;
50 |
51 | $ret = sprintf('%d%d', $vl1, $vl2) == substr($input, -2);
52 | }
53 |
54 | return $ret;
55 | }
56 |
57 | public function message()
58 | {
59 | return 'O campo :attribute não é uma carteira nacional de habilitação válida.';
60 | }
61 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Cnpj.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class Cnpj implements Rule
11 | {
12 |
13 |
14 |
15 | /**
16 | * Valida se o CNPJ é válido
17 | *
18 | * @param string $attribute
19 | * @param string $value
20 | * @return boolean
21 | */
22 | public function passes($attribute, $value)
23 | {
24 | $c = preg_replace('/\D/', '', $value);
25 |
26 | $b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
27 |
28 | if (strlen($c) != 14) {
29 | return false;
30 |
31 | }
32 |
33 | // Remove sequências repetidas como "111111111111"
34 | // https://github.com/LaravelLegends/pt-br-validator/issues/4
35 |
36 | elseif (preg_match("/^{$c[0]}{14}$/", $c) > 0) {
37 |
38 | return false;
39 | }
40 |
41 | for ($i = 0, $n = 0; $i < 12; $n += $c[$i] * $b[++$i]);
42 |
43 | if ($c[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
44 | return false;
45 | }
46 |
47 | for ($i = 0, $n = 0; $i <= 12; $n += $c[$i] * $b[$i++]);
48 |
49 | if ($c[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
50 | return false;
51 | }
52 |
53 | return true;
54 |
55 | }
56 |
57 |
58 | public function message()
59 | {
60 | return 'O campo :attribute não é um CNPJ válido.';
61 | }
62 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Cns.php:
--------------------------------------------------------------------------------
1 |
12 | */
13 | class Cns implements Rule
14 | {
15 |
16 | public function passes($attribute, $cns)
17 | {
18 | if (!isset($cns[0])) return false;
19 |
20 | $digit = (int) $cns[0];
21 |
22 | // Validamos se possui 15 caracteres ou se são 15 sequenciais repetidos
23 |
24 | if (strlen($cns) != 15 || preg_match("/^{$digit}{15}$/", $cns) > 0) {
25 | return false;
26 | }
27 |
28 | return $digit >= 7 ? $this->cnsProv($cns) : $this->cns($cns);
29 | }
30 |
31 | public function message()
32 | {
33 | return 'O campo :attribute não é um CNS válido.';
34 | }
35 |
36 | /**
37 | * Valida o CNS menor que 7 no primeiro dígito
38 | * @param string $cns
39 | * @return bool
40 | */
41 |
42 | protected function cns(string $cns)
43 | {
44 |
45 | $pis = substr($cns, 0, 11);
46 |
47 | for ($soma = 0, $i = 0, $j = 15; $i <= 10; $i++, $j--) {
48 | $soma += intval($pis[$i]) * $j;
49 | }
50 |
51 | $dv = 11 - ($soma % 11);
52 |
53 | $dv != 11 ?: $dv = 0;
54 |
55 | if ($dv === 10) {
56 |
57 | for ($soma = 2, $i = 1, $j = 15; $i <= 10; $i++, $j--) {
58 | $soma += intval(substr($pis, $i - 1, $i)) * $j;
59 | }
60 |
61 | $dv = 11 - ($soma % 11);
62 |
63 | $dv != 11 ?: $dv = 0;
64 |
65 | $resultado = $pis . "001" . (string) $dv;
66 |
67 | } else {
68 | $resultado = $pis . "000" . (string) $dv;
69 | }
70 |
71 | return $cns === $resultado;
72 | }
73 |
74 | /**
75 | * Valida o CNS que inicia por 7, 8 ou 9
76 | * @param string $cns
77 | */
78 | protected function cnsProv(string $cns)
79 | {
80 | if (strlen($cns) != 15) return false;
81 |
82 | for ($s = 0, $i = 0, $j = 15; $i < 15; $i++, $j--) {
83 | $s += intval($cns[$i]) * $j;
84 | }
85 |
86 | return $s % 11 === 0;
87 | }
88 | }
89 |
90 |
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Cpf.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class Cpf implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida se o CPF é válido
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 |
22 | public function passes($attribute, $value)
23 | {
24 | $c = preg_replace('/\D/', '', $value);
25 |
26 | if (strlen($c) != 11 || preg_match("/^{$c[0]}{11}$/", $c)) {
27 | return false;
28 | }
29 |
30 | for ($s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--);
31 |
32 | if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
33 | return false;
34 | }
35 |
36 | for ($s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--);
37 |
38 | if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
39 | return false;
40 | }
41 |
42 | return true;
43 | }
44 |
45 | public function message()
46 | {
47 | return 'O campo :attribute não é um CPF válido.';
48 | }
49 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/CpfOuCnpj.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class CpfOuCnpj implements Rule
11 | {
12 | /**
13 | * Valida se o campo é um CPF ou um CNPJ válido
14 | *
15 | * @param string $attribute
16 | * @param string $value
17 | * @return boolean
18 | */
19 | public function passes($attribute, $value)
20 | {
21 |
22 | return (new Cpf)->passes($attribute, $value) || (new Cnpj)->passes($attribute, $value);
23 | }
24 |
25 | public function message()
26 | {
27 | return 'O campo :attribute não é um CPF ou CNPJ válido.';
28 | }
29 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/FormatoCep.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class FormatoCep implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida se o formato de CEP está correto
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 |
22 | public function passes($attribute, $value)
23 | {
24 | return preg_match('/^\d{2}\.?\d{3}-\d{3}$/', $value) > 0;
25 | }
26 |
27 | public function message()
28 | {
29 | return 'O campo :attribute não possui um formato válido de CEP.';
30 | }
31 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/FormatoCnpj.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class FormatoCnpj implements Rule
11 | {
12 |
13 |
14 | /**
15 | *
16 | * Valida o formato do cnpj
17 | *
18 | * @param string $attribute
19 | * @param string $value
20 | * @return boolean
21 | */
22 | public function passes($attribute, $value)
23 | {
24 | return preg_match('/^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/', $value) > 0;
25 | }
26 |
27 | public function message()
28 | {
29 | return 'O campo :attribute não possui o formato válido de CNPJ.';
30 | }
31 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/FormatoCpf.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class FormatoCpf implements Rule
11 | {
12 |
13 | /**
14 | * Valida o formato do cpf
15 | *
16 | * @param string $attribute
17 | * @param string $value
18 | * @return boolean
19 | */
20 | public function passes($attribute, $value)
21 | {
22 | return preg_match('/^\d{3}\.\d{3}\.\d{3}-\d{2}$/', $value) > 0;
23 | }
24 |
25 | public function message()
26 | {
27 | return 'O campo :attribute não possui o formato válido de CPF.';
28 | }
29 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/FormatoCpfOuCnpj.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class FormatoCpfOuCnpj implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida o formato de CPF ou CNPJ
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 | public function passes($attribute, $value)
22 | {
23 | return (new FormatoCpf)->passes($attribute, $value) || (new FormatoCnpj)->passes($attribute, $value);
24 | }
25 |
26 | public function message()
27 | {
28 | return 'O campo :attribute não possui o formato válido de CPF ou CNPJ.';
29 | }
30 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/FormatoPis.php:
--------------------------------------------------------------------------------
1 |
11 | */
12 | class FormatoPis implements Rule
13 | {
14 |
15 | /**
16 | * Valida o formato do Número do PIS
17 | *
18 | * @param string $attribute
19 | * @param string $value
20 | * @return boolean
21 | */
22 | public function passes($attribute, $value)
23 | {
24 | return preg_match('/^\d{3}\.\d{5}\.\d{2}-\d{1}$/', $value) > 0;
25 | }
26 |
27 | public function message()
28 | {
29 | return 'O campo :attribute não é um PIS com formato válido.';
30 | }
31 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/FormatoPlacaDeVeiculo.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class FormatoPlacaDeVeiculo implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida se o formato de placa de veículo está correto.
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 |
22 | public function passes($attribute, $value)
23 | {
24 | return preg_match('/^[a-zA-Z]{3}\-?[0-9][0-9a-zA-Z][0-9]{2}$/', $value) > 0;
25 | }
26 |
27 |
28 | public function message()
29 | {
30 | return 'O campo :attribute não possui um formato válido de placa de veículo.';
31 | }
32 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Pis.php:
--------------------------------------------------------------------------------
1 |
12 | */
13 |
14 | class Pis implements Rule
15 | {
16 |
17 | /**
18 | * Valida o formato do Número do PIS
19 | *
20 | * @param string $attribute
21 | * @param string $value
22 | * @return boolean
23 | */
24 | public function passes($attribute, $value)
25 | {
26 | $digits = (string) preg_replace('/\D/', '', (string) $value);
27 |
28 | if (mb_strlen($digits) != 11 || preg_match('/^' . $digits[0] . '{11}$/', $digits)) {
29 | return false;
30 | }
31 |
32 | $multipliers = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
33 |
34 | $sum = 0;
35 |
36 | for ($position = 0; $position < 10; ++$position) {
37 | $sum += (int) $digits[$position] * $multipliers[$position];
38 | }
39 |
40 | $mod = $sum % 11;
41 |
42 | return (int) $digits[10] === ($mod < 2 ? 0 : 11 - $mod);
43 | }
44 |
45 | public function message()
46 | {
47 | return 'O campo :attribute não é um PIS válido.';
48 | }
49 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Telefone.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class Telefone implements Rule
11 | {
12 |
13 | /**
14 | * Valida o formato do telefone
15 | *
16 | * @param string $attribute
17 | * @param string $value
18 | * @return boolean
19 | */
20 | public function passes($attribute, $value)
21 | {
22 | return preg_match('/^\d{4}-\d{4}$/', $value) > 0;
23 | }
24 |
25 |
26 | public function message()
27 | {
28 | return 'O campo :attribute não é um telefone válido.';
29 | }
30 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/TelefoneComCodigo.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class TelefoneComCodigo implements Rule
11 | {
12 |
13 |
14 | /**
15 | * Valida o formato do telefone com código do país
16 | *
17 | * @param string $attribute
18 | * @param string $value
19 | * @return boolean
20 | */
21 | public function passes($attribute, $value)
22 | {
23 | return preg_match('/^[+]\d{1,2}\s?\(\d{2}\)\s?\d{4,5}\-\d{4}$/', $value) > 0;
24 | }
25 |
26 |
27 | public function message()
28 | {
29 | return 'O campo :attribute não é um telefone com código e DDD válido.';
30 | }
31 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/TelefoneComDdd.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class TelefoneComDdd implements Rule
11 | {
12 |
13 | /**
14 | * Valida o formato do telefone junto com o ddd
15 | *
16 | * @param string $attribute
17 | * @param string $value
18 | * @return boolean
19 | */
20 |
21 | public function passes($attribute, $value)
22 | {
23 | return preg_match('/^\(\d{2}\)\s?\d{4}-\d{4}$/', $value) > 0;
24 | }
25 |
26 |
27 | public function message()
28 | {
29 | return 'O campo :attribute não é um telefone com DDD válido.';
30 | }
31 | }
--------------------------------------------------------------------------------
/src/pt-br-validator/Rules/Uf.php:
--------------------------------------------------------------------------------
1 |
9 | */
10 | class Uf implements Rule
11 | {
12 | const ESTADOS = [
13 | 'AC' => 'Acre',
14 | 'AL' => 'Alagoas',
15 | 'AP' => 'Amapá',
16 | 'AM' => 'Amazonas',
17 | 'BA' => 'Bahia',
18 | 'CE' => 'Ceará',
19 | 'DF' => 'Distrito Federal',
20 | 'ES' => 'Espirito Santo',
21 | 'GO' => 'Goiás',
22 | 'MA' => 'Maranhão',
23 | 'MS' => 'Mato Grosso do Sul',
24 | 'MT' => 'Mato Grosso',
25 | 'MG' => 'Minas Gerais',
26 | 'PA' => 'Pará',
27 | 'PB' => 'Paraíba',
28 | 'PR' => 'Paraná',
29 | 'PE' => 'Pernambuco',
30 | 'PI' => 'Piauí',
31 | 'RJ' => 'Rio de Janeiro',
32 | 'RN' => 'Rio Grande do Norte',
33 | 'RS' => 'Rio Grande do Sul',
34 | 'RO' => 'Rondônia',
35 | 'RR' => 'Roraima',
36 | 'SC' => 'Santa Catarina',
37 | 'SP' => 'São Paulo',
38 | 'SE' => 'Sergipe',
39 | 'TO' => 'Tocantins',
40 | ];
41 |
42 | /**
43 | * Valida se o UF é válido
44 | *
45 | * @param string $attribute
46 | * @param string $value
47 | * @return boolean
48 | */
49 | public function passes($attribute, $value)
50 | {
51 | return isset(static::ESTADOS[$value]);
52 | }
53 |
54 | /**
55 | *
56 | * @return string
57 | */
58 | public function message()
59 | {
60 | return 'O campo :attribute não é um UF válido.';
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/pt-br-validator/ValidatorProvider.php:
--------------------------------------------------------------------------------
1 | \LaravelLegends\PtBrValidator\Rules\Celular::class,
28 | 'celular_com_ddd' => \LaravelLegends\PtBrValidator\Rules\CelularComDdd::class,
29 | 'celular_com_codigo' => \LaravelLegends\PtBrValidator\Rules\CelularComCodigo::class,
30 | 'celular_com_codigo_sem_mascara' => \LaravelLegends\PtBrValidator\Rules\CelularComCodigoSemMascara::class,
31 | 'cnh' => \LaravelLegends\PtBrValidator\Rules\Cnh::class,
32 | 'cnpj' => \LaravelLegends\PtBrValidator\Rules\Cnpj::class,
33 | 'cns' => \LaravelLegends\PtBrValidator\Rules\Cns::class,
34 | 'cpf' => \LaravelLegends\PtBrValidator\Rules\Cpf::class,
35 | 'formato_cnpj' => \LaravelLegends\PtBrValidator\Rules\FormatoCnpj::class,
36 | 'formato_cpf' => \LaravelLegends\PtBrValidator\Rules\FormatoCpf::class,
37 | 'telefone' => \LaravelLegends\PtBrValidator\Rules\Telefone::class,
38 | 'telefone_com_ddd' => \LaravelLegends\PtBrValidator\Rules\TelefoneComDdd::class,
39 | 'telefone_com_codigo' => \LaravelLegends\PtBrValidator\Rules\TelefoneComCodigo::class,
40 | 'formato_cep' => \LaravelLegends\PtBrValidator\Rules\FormatoCep::class,
41 | 'formato_placa_de_veiculo' => \LaravelLegends\PtBrValidator\Rules\FormatoPlacaDeVeiculo::class,
42 | 'formato_pis' => \LaravelLegends\PtBrValidator\Rules\FormatoPis::class,
43 | 'pis' => \LaravelLegends\PtBrValidator\Rules\Pis::class,
44 | 'cpf_ou_cnpj' => \LaravelLegends\PtBrValidator\Rules\CpfOuCnpj::class,
45 | 'formato_cpf_ou_cnpj' => \LaravelLegends\PtBrValidator\Rules\FormatoCpfOuCnpj::class,
46 | 'uf' => \LaravelLegends\PtBrValidator\Rules\Uf::class,
47 | ];
48 |
49 | foreach ($rules as $name => $class) {
50 | $rule = new $class;
51 |
52 | $extension = static function ($attribute, $value) use ($rule) {
53 | return $rule->passes($attribute, $value);
54 | };
55 |
56 | $this->app['validator']->extend($name, $extension, $rule->message());
57 | }
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/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LaravelLegends/pt-br-validator/07efbf2684c95bc7f53edaf265e996d1a493b21e/tests/.gitkeep
--------------------------------------------------------------------------------
/tests/Unit/TestRules.php:
--------------------------------------------------------------------------------
1 | '99999-5555'
10 | ], [
11 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Celular]
12 | ]);
13 |
14 |
15 | $this->assertTrue($validator->passes());
16 | }
17 |
18 | public function testCelularComDdd()
19 | {
20 | $validator = \Validator::make([
21 | 'valido' => '(31)99999-5555'
22 | ], [
23 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\CelularComDdd]
24 | ]);
25 |
26 |
27 | $this->assertTrue($validator->passes());
28 | }
29 |
30 |
31 | public function testCelularComCodigo()
32 | {
33 | $validator = \Validator::make([
34 | 'valido' => '+1(31)99999-5555'
35 | ], [
36 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\CelularComCodigo]
37 | ]);
38 |
39 |
40 | $this->assertTrue($validator->passes());
41 | }
42 |
43 | public function testTelefone()
44 | {
45 | $validator = \Validator::make([
46 | 'valido' => '9999-5555'
47 | ], [
48 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Telefone]
49 | ]);
50 |
51 |
52 | $this->assertTrue($validator->passes());
53 | }
54 |
55 |
56 |
57 | public function testTelefoneComDdd()
58 | {
59 | $validator = \Validator::make([
60 | 'valido' => '(31)9999-5555'
61 | ], [
62 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\TelefoneComDdd]
63 | ]);
64 |
65 |
66 | $this->assertTrue($validator->passes());
67 | }
68 |
69 |
70 |
71 |
72 |
73 | public function testTelefoneComCodigo()
74 | {
75 | $validator = \Validator::make([
76 | 'valido' => '+66(31)9999-5555'
77 | ], [
78 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\TelefoneComCodigo]
79 | ]);
80 |
81 |
82 | $this->assertTrue($validator->passes());
83 | }
84 |
85 |
86 | public function testCpf()
87 | {
88 | $validator = \Validator::make([
89 | 'valido' => '98136622809'
90 | ], [
91 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cpf]
92 | ]);
93 |
94 | $this->assertTrue($validator->passes());
95 |
96 | $validator = \Validator::make([
97 | 'invalido' => '08136622809'
98 | ], [
99 | 'invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cpf]
100 | ]);
101 |
102 | $this->assertTrue($validator->fails());
103 | }
104 |
105 |
106 | public function testFormatoCpf()
107 | {
108 | $validator = \Validator::make([
109 | 'valido' => '981.366.228-09'
110 | ], [
111 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoCpf]
112 | ]);
113 |
114 | $this->assertTrue($validator->passes());
115 |
116 | $validator = \Validator::make([
117 | 'invalido' => '08136622809'
118 | ], [
119 | 'invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoCpf]
120 | ]);
121 |
122 | $this->assertTrue($validator->fails());
123 | }
124 |
125 |
126 |
127 | public function testCnpj()
128 | {
129 | $validator = \Validator::make([
130 | 'valido' => '16.651.801/0001-57'
131 | ], [
132 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cnpj]
133 | ]);
134 |
135 | $this->assertTrue($validator->passes());
136 |
137 | $validator = \Validator::make([
138 | 'invalido' => '16.651.801/0001-52'
139 | ], [
140 | 'invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cnpj]
141 | ]);
142 |
143 | $this->assertTrue($validator->fails());
144 | }
145 |
146 |
147 |
148 | public function testFormatoCnpj()
149 | {
150 | $validator = \Validator::make([
151 | 'valido' => '16.651.801/0001-57'
152 | ], [
153 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoCnpj]
154 | ]);
155 |
156 | $this->assertTrue($validator->passes());
157 |
158 | $validator = \Validator::make([
159 | 'invalido' => '16.651.801/000152'
160 | ], [
161 | 'invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoCnpj]
162 | ]);
163 |
164 | $this->assertTrue($validator->fails());
165 | }
166 |
167 |
168 | public function testFormatoPlacaDeVeiculo()
169 | {
170 | $validator = \Validator::make([
171 | 'valido' => 'BEE4R22'
172 | ], [
173 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoPlacaDeVeiculo]
174 | ]);
175 |
176 | $this->assertTrue($validator->passes());
177 |
178 | $validator = \Validator::make([
179 | 'invalido' => 'XXXBEE4R22'
180 | ], [
181 | 'invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoPlacaDeVeiculo]
182 | ]);
183 |
184 | $this->assertTrue($validator->fails());
185 | }
186 |
187 |
188 |
189 | public function testCnh()
190 | {
191 | $validator = \Validator::make([
192 | 'valido' => '96784547943'
193 | ], [
194 | 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cnh]
195 | ]);
196 |
197 | $this->assertTrue($validator->passes());
198 |
199 | $validator = \Validator::make([
200 | 'invalido' => '96784547999'
201 | ], [
202 | 'invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cnh]
203 | ]);
204 |
205 | $this->assertTrue($validator->fails());
206 | }
207 |
208 | public function testFormatoPis()
209 | {
210 | $validator = \Validator::make(['valido' => '276.96730.83-0'], [ 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoPis]]);
211 |
212 | $this->assertTrue($validator->passes());
213 |
214 | $validator = \Validator::make(['valido' => '276.96730.830'], [ 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoPis]]);
215 |
216 | $this->assertTrue($validator->fails());
217 | }
218 |
219 |
220 | public function testPis()
221 | {
222 |
223 | foreach (['690.30244.88-6', '042.33768.05-2', '971.78508.77-5'] as $pis) {
224 |
225 | $validator = \Validator::make(['valido' => $pis], [ 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Pis]]);
226 |
227 | $this->assertTrue($validator->passes());
228 | }
229 |
230 |
231 | $validator = \Validator::make(['valido' => '290.30244.88-5'], [ 'valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Pis]]);
232 |
233 | $this->assertTrue($validator->fails());
234 | }
235 |
236 |
237 | public function testCpfOuCnpj()
238 | {
239 |
240 |
241 | foreach (['981.366.228-09', '56.611.605/0001-73', '49851807000127'] as $valor) {
242 |
243 | $validator = \Validator::make(
244 | ['valido' => $valor],
245 | ['valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\CpfOuCnpj]]
246 | );
247 |
248 | $this->assertTrue($validator->passes());
249 | }
250 |
251 | foreach (['000.366.228-09', '11.611.605/0001-73', '22851807000127'] as $valor) {
252 |
253 | $validator = \Validator::make(
254 | ['invalido' => $valor],
255 | ['invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\CpfOuCnpj]]
256 | );
257 |
258 | $this->assertTrue($validator->fails());
259 | }
260 | }
261 |
262 |
263 | public function testFormatoCpfOuCnpj()
264 | {
265 |
266 |
267 | foreach (['981.366.228-09', '000.000.000-00', '56.611.605/0001-73'] as $valor) {
268 |
269 | $validator = \Validator::make(
270 | ['valido' => $valor],
271 | ['valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoCpfOuCnpj]]
272 | );
273 |
274 | $this->assertTrue($validator->passes());
275 | }
276 |
277 | foreach (['0000.366.228-09', '11.6211.605/0001-73', '22851807000127'] as $valor) {
278 |
279 | $validator = \Validator::make(
280 | ['invalido' => $valor],
281 | ['invalido' => ['required', new \LaravelLegends\PtBrValidator\Rules\FormatoCpfOuCnpj]]
282 | );
283 |
284 | $this->assertTrue($validator->fails());
285 | }
286 | }
287 |
288 |
289 | public function testCns()
290 | {
291 | foreach ([
292 | '272004493990007',
293 | '140776230420006',
294 | '254446765170004',
295 | '912176122180009',
296 | '174295560290007',
297 | '103409299850000',
298 | '773398431180002',
299 | ] as $valor) {
300 |
301 | $validator = \Validator::make(
302 | ['valido' => $valor],
303 | ['valido' => ['required', new \LaravelLegends\PtBrValidator\Rules\Cns]]
304 | );
305 |
306 | $this->assertTrue($validator->passes(), "O número $valor é inválido");
307 | }
308 |
309 | foreach ([
310 | '072004493990007',
311 | '000000000000000',
312 | '111111111111111',
313 | '222222222222222',
314 | '999999999999999',
315 | '123456789123456'
316 |
317 | ] as $valor) {
318 |
319 | $validator = \Validator::make(
320 | ['valido' => $valor],
321 | ['valido' => [new \LaravelLegends\PtBrValidator\Rules\Cns]]
322 | );
323 |
324 | $this->assertTrue($validator->fails(), "O número $valor é VERDADEIRO");
325 | }
326 | }
327 | }
--------------------------------------------------------------------------------
/tests/Unit/TestValidator.php:
--------------------------------------------------------------------------------
1 | '(99)3500-4444'],
17 | ['certo' => 'telefone-com-ddd']
18 | );
19 |
20 | $incorrect = Validator::make(
21 | ['errado' => '(99)9-1926'],
22 | ['errado' => 'telefone-com-ddd']
23 | );
24 |
25 | $this->assertTrue($correct->passes());
26 |
27 | $this->assertTrue($incorrect->fails());
28 | }
29 |
30 | public function testTelefoneComCodigo()
31 | {
32 | $correct = Validator::make(
33 | ['certo' => '+55(99)3500-4444'],
34 | ['certo' => 'telefone-com-codigo']
35 | );
36 |
37 | $incorrect = Validator::make(
38 | ['errado' => '+5(99)9-1926'],
39 | ['errado' => 'telefone-com-codigo']
40 | );
41 |
42 | $this->assertTrue($correct->passes());
43 |
44 | $this->assertTrue($incorrect->fails());
45 | }
46 |
47 | public function testCelularComDdd()
48 | {
49 | $correct = Validator::make(
50 | ['certo' => '(99)98899-4444'],
51 | ['certo' => 'celular-com-ddd']
52 | );
53 |
54 | $incorrect = Validator::make(
55 | ['errado' => '(99)800-1926'],
56 | ['errado' => 'celular-com-ddd']
57 | );
58 |
59 | $this->assertTrue($correct->passes());
60 |
61 | $this->assertTrue($incorrect->fails());
62 | }
63 |
64 | public function testCelularComCodigo()
65 | {
66 | $correct = Validator::make(
67 | ['certo' => '+55(99)98899-4444'],
68 | ['certo' => 'celular-com-codigo']
69 | );
70 |
71 | $incorrect = Validator::make(
72 | ['errado' => '+5(99)800-1926'],
73 | ['errado' => 'celular-com-codigo']
74 | );
75 |
76 | $this->assertTrue($correct->passes());
77 |
78 | $this->assertTrue($incorrect->fails());
79 | }
80 |
81 |
82 | public function testCelular()
83 | {
84 | $correct = Validator::make(
85 | ['certo' => '98899-4444', 'outro_certo' => '9800-1936'],
86 | ['certo' => 'celular', 'outro_certo' => 'celular']
87 | );
88 |
89 | $incorrect = Validator::make(
90 | ['errado' => '900-1926'],
91 | ['errado' => 'celular']
92 | );
93 |
94 | $this->assertTrue($correct->passes());
95 |
96 | $this->assertTrue($incorrect->fails());
97 | }
98 |
99 | public function testTelefone()
100 | {
101 | $correct = Validator::make(
102 | ['certo' => '3598-4550'],
103 | ['certo' => 'telefone']
104 | );
105 |
106 | $incorrect = Validator::make(
107 | ['errado' => '99800-1926'],
108 | ['errado' => 'telefone']
109 | );
110 |
111 | $this->assertTrue($correct->passes());
112 |
113 | $this->assertTrue($incorrect->fails());
114 | }
115 |
116 |
117 | public function testCpf()
118 | {
119 | $correct = Validator::make(
120 | ['certo' => '094.050.986-59'],
121 | ['certo' => 'cpf']
122 | );
123 |
124 | $incorrect = Validator::make(
125 | ['errado' => '99800-1926'],
126 | ['errado' => 'cpf']
127 | );
128 |
129 | $this->assertTrue($correct->passes());
130 |
131 | $this->assertTrue($incorrect->fails());
132 | }
133 |
134 | public function testCpfFormato()
135 | {
136 | $correct = Validator::make(
137 | ['certo' => '094.050.986-59'],
138 | ['certo' => 'formato-cpf']
139 | );
140 |
141 | $incorrect = Validator::make(
142 | ['errado' => '094.050.986-591'],
143 | ['errado' => 'formato-cpf']
144 | );
145 |
146 | $this->assertTrue($correct->passes());
147 |
148 | $this->assertTrue($incorrect->fails());
149 | }
150 |
151 |
152 | public function testCnpj()
153 | {
154 | $correct = Validator::make(
155 | ['certo' => '53.084.587/0001-20'],
156 | ['certo' => 'cnpj']
157 | );
158 |
159 | $incorrect = Validator::make(
160 | ['errado' => '51.084.587/0001-20'],
161 | ['errado' => 'cnpj']
162 | );
163 |
164 | $this->assertTrue($correct->passes());
165 |
166 | $this->assertTrue($incorrect->fails());
167 |
168 |
169 | // Correção do ISSUE: https://github.com/LaravelLegends/pt-br-validator/issues/4
170 |
171 | $repeats = [
172 | '00.000.000/0000-00',
173 | '11111111111111',
174 | '22222222222222',
175 | '00.000.000/0000-00',
176 | '11.111.111/1111-11',
177 | '22.222.222/2222-22',
178 | ];
179 |
180 | foreach ($repeats as $cnpj) {
181 | $validator = Validator::make(['cnpj' => $cnpj], [
182 | 'cnpj' => 'required|cnpj'
183 | ]);
184 |
185 | $this->assertFalse($validator->passes(), "O CNPJ $cnpj foi marcado como verdadeiro, quando na verdade é FALSO");
186 | }
187 | }
188 |
189 |
190 | public function testCnpjFormato()
191 | {
192 | $correct = Validator::make(
193 | ['certo' => '53.084.587/0001-20'],
194 | ['certo' => 'formato-cnpj']
195 | );
196 |
197 | $incorrect = Validator::make(
198 | ['errado' => '51.084.587/000120'],
199 | ['errado' => 'formato-cnpj']
200 | );
201 |
202 | $this->assertTrue($correct->passes());
203 |
204 | $this->assertTrue($incorrect->fails());
205 | }
206 |
207 | public function testCnh()
208 | {
209 | $correct = Validator::make(
210 | ['certo' => '96784547943'],
211 | ['certo' => 'cnh']
212 | );
213 |
214 | $incorrect = Validator::make(
215 | ['errado' => '96784547999'],
216 | ['errado' => 'cnh']
217 | );
218 |
219 | $this->assertTrue($correct->passes());
220 |
221 | $this->assertTrue($incorrect->fails());
222 | }
223 |
224 |
225 | public function testFormatoCep()
226 | {
227 | $cepsValidos = [
228 | '32400-000',
229 | '32.400-000',
230 | '07.550-000',
231 | '30.150-150'
232 | ];
233 |
234 |
235 | foreach ($cepsValidos as $cep) {
236 | $correct = Validator::make(['cep' => $cep], ['cep' => 'formato_cep']);
237 |
238 | $this->assertTrue($correct->passes());
239 | }
240 |
241 | $cepsInvalidos = [
242 | '32400.000',
243 | '32.400-0000',
244 | '0.400-000',
245 | '300.40-000',
246 | '300.400-000'
247 | ];
248 |
249 |
250 | foreach ($cepsInvalidos as $cep) {
251 | $correct = Validator::make(['cep' => $cep], ['cep' => 'formato_cep']);
252 |
253 | $this->assertTrue($correct->fails());
254 | }
255 | }
256 |
257 | public function testFormatoPlacaDeVeiculo()
258 | {
259 | $placasValidas = [
260 | 'ABC-1234',
261 | 'abc-1234',
262 | 'ABC1234',
263 | 'aBc1234',
264 | 'abc1234',
265 |
266 | // placas mercosul
267 | 'BEE4R22',
268 | 'FUM-0B05',
269 | 'FUM-5L58',
270 | ];
271 |
272 | foreach ($placasValidas as $placa) {
273 | $correct = Validator::make(
274 | ['placa' => $placa],
275 | ['placa' => 'formato_placa_de_veiculo']
276 | );
277 |
278 | $this->assertTrue($correct->passes());
279 | }
280 |
281 | $placasInvalidas = [
282 | 'a2c-1234',
283 | 'abc-12ed',
284 | 'abc 1234',
285 | 'ãBC1234',
286 | 'ABCD1234',
287 | 'ABC12345',
288 | 'ab1234',
289 | 'ab123a4',
290 | 'abc+1234'
291 | ];
292 |
293 | foreach ($placasInvalidas as $placa) {
294 | $incorrect = Validator::make(
295 | ['placa' => $placa],
296 | ['placa' => 'formato_placa_de_veiculo']
297 | );
298 |
299 | $this->assertTrue($incorrect->fails());
300 | }
301 | }
302 |
303 |
304 |
305 | public function testFormatoPis()
306 | {
307 | $validator = Validator::make(['valido' => '276.96730.83-0'], [ 'valido' => 'formato_pis' ]);
308 |
309 | $this->assertTrue($validator->passes());
310 |
311 | $validator = Validator::make(['valido' => '276.96730.830'], [ 'valido' => 'formato_pis' ]);
312 |
313 | $this->assertTrue($validator->fails());
314 | }
315 |
316 |
317 | public function testPis()
318 | {
319 | foreach (['690.30244.88-6', '042.33768.05-2', '971.78508.77-5'] as $pis) {
320 | $validator = Validator::make(['valido' => $pis], [ 'valido' => 'pis']);
321 |
322 | $this->assertTrue($validator->passes());
323 | }
324 |
325 |
326 | $validator = Validator::make(['valido' => '290.30244.88-5'], [ 'valido' => 'pis' ]);
327 |
328 | $this->assertTrue($validator->fails());
329 | }
330 |
331 | public function testCpfOuCnpj()
332 | {
333 | foreach (['981.366.228-09', '56.611.605/0001-73', '49851807000127'] as $valor) {
334 | $validator = Validator::make(
335 | ['valido' => $valor],
336 | ['valido' => 'cpf_ou_cnpj']
337 | );
338 |
339 | $this->assertTrue($validator->passes());
340 | }
341 |
342 | foreach (['000.366.228-09', '11.611.605/0001-73', '22851807000127'] as $valor) {
343 | $validator = Validator::make(
344 | ['invalido' => $valor],
345 | ['invalido' => 'cpf_ou_cnpj']
346 | );
347 |
348 | $this->assertTrue($validator->fails());
349 | }
350 | }
351 |
352 |
353 | public function testFormatoCpfOuCnpj()
354 | {
355 | foreach (['981.366.228-09', '000.000.000-00', '56.611.605/0001-73'] as $valor) {
356 | $validator = Validator::make(
357 | ['valido' => $valor],
358 | ['valido' => 'formato_cpf_ou_cnpj']
359 | );
360 |
361 | $this->assertTrue($validator->passes());
362 | }
363 |
364 | foreach (['0000.366.228-09', '11.6211.605/0001-73', '22851807000127'] as $valor) {
365 | $validator = Validator::make(
366 | ['invalido' => $valor],
367 | ['invalido' => 'formato_cpf_ou_cnpj']
368 | );
369 |
370 | $this->assertTrue($validator->fails());
371 | }
372 | }
373 |
374 | public function testUf()
375 | {
376 | $testes = [
377 | 'AC' => true,
378 | 'AL' => true,
379 | 'AP' => true,
380 | 'AM' => true,
381 | 'BA' => true,
382 | 'CE' => true,
383 | 'DF' => true,
384 | 'ES' => true,
385 | 'GO' => true,
386 | 'MA' => true,
387 | 'MS' => true,
388 | 'MT' => true,
389 | 'MG' => true,
390 | 'PA' => true,
391 | 'PB' => true,
392 | 'PR' => true,
393 | 'PE' => true,
394 | 'PI' => true,
395 | 'RJ' => true,
396 | 'RN' => true,
397 | 'RS' => true,
398 | 'RO' => true,
399 | 'RR' => true,
400 | 'SC' => true,
401 | 'SP' => true,
402 | 'SE' => true,
403 | 'TO' => true,
404 |
405 | 'FALSE' => false,
406 | 'mg' => false,
407 | 'sp' => false,
408 | 'MO' => false,
409 | 'CB' => false,
410 | ];
411 |
412 | foreach ($testes as $valor => $boolean) {
413 | $validator = Validator::make(
414 | ['valido' => $valor],
415 | ['valido' => 'uf']
416 | );
417 |
418 | $this->assertTrue($boolean ? $validator->passes() : $validator->fails());
419 | }
420 | }
421 |
422 |
423 | public function testCns()
424 | {
425 | foreach ([
426 | '272004493990007',
427 | '140776230420006',
428 | '254446765170004',
429 | '912176122180009',
430 | '174295560290007',
431 | '103409299850000',
432 | '773398431180002',
433 | ] as $valor) {
434 |
435 | $validator = Validator::make(
436 | ['valido' => $valor],
437 | ['valido' => ['required', 'cns']]
438 | );
439 |
440 | $this->assertTrue($validator->passes(), "O número $valor é inválido");
441 | }
442 |
443 | foreach ([
444 | '072004493990007',
445 | '000000000000000',
446 | '111111111111111',
447 | '222222222222222',
448 | '999999999999999',
449 | '123456789123456'
450 |
451 | ] as $valor) {
452 |
453 | $validator = Validator::make(
454 | ['valido' => $valor],
455 | ['valido' => ['required', 'cns']]
456 | );
457 |
458 | $this->assertTrue($validator->fails(), "O número $valor é VERDADEIRO");
459 | }
460 | }
461 | }
462 |
--------------------------------------------------------------------------------
/tests/ValidatorTestCase.php:
--------------------------------------------------------------------------------
1 | app->register(\LaravelLegends\PtBrValidator\ValidatorProvider::class);
10 | }
11 | }
--------------------------------------------------------------------------------
/tests/coverage/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------