Last active
December 30, 2019 13:12
-
-
Save jorgecrodrigues/bdc7710988695f20b10cbd50c52ff133 to your computer and use it in GitHub Desktop.
Regras de validação para CPF e CNPJ usando Validator usando Laravel 5.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use Illuminate\Support\ServiceProvider; | |
use Illuminate\Support\Facades\Validator; | |
class AppServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
// Regra de validação de CPF usando regex. | |
Validator::extendImplicit('cpf', function ($attribute, $value, $parameters, $validator) { | |
// Extrai somente os números da string. | |
$numbers = preg_replace('/[^0-9]/is', '', $value); | |
// Verifica se foi informado todos os digitos corretamente. | |
// Verifica se foi informado uma sequência de digitos repetidos. EX: 111.111.111-11 | |
if (strlen($numbers) === 11 && preg_match('/(\d)\1{10}/', $numbers)) return false; | |
// Faz o cálculo para validar o CPF. | |
// Percorre do nono até o décimo dígito. | |
for ($i = 9; $i < 11; $i++) { | |
for ($d = 0, $c = 0; $c < $i; $c++) { | |
$d += $numbers{$c} * (($i + 1) - $c); | |
} | |
$d = ((10 * $d) % 11) % 10; | |
if ($numbers{$c} != $d) { | |
return false; | |
} | |
} | |
return true; | |
}); | |
// Regra de validação de CNPJ usando regex. | |
Validator::extendImplicit('cnpj', function ($attribute, $value, $parameters, $validator) { | |
// Extrai somente os números da string. | |
$numbers = preg_replace('/[^0-9]/is', '', $value); | |
// Verifica se foi informado todos os digitos corretamente. | |
// Verifica se foi informado uma sequência de digitos repetidos. EX: 11.111.111/1111-11 | |
if (strlen($numbers) === 14 && preg_match('/(\d)\1{13}/', $numbers)) return false; | |
// Faz o cálculo para validar o CNPJ. | |
// Faz a validação do primeiro dígito verificador. | |
for ($i = 0, $j = 5, $sum = 0; $i < 12; $i++) { | |
$sum += $numbers{$i} * $j; | |
$j = ($j === 2) ? 9 : $j - 1; | |
} | |
$rest = $sum % 11; | |
if ($numbers{12} != $rest < 2 ? 0 : 11 - $rest) return false; | |
// Faz a validação do segundo dígito verificador. | |
for ($i = 0, $j = 6, $sum = 0; $i < 13; $i++) { | |
$sum += $numbers{$i} * $j; | |
$j = ($j === 2) ? 9 : $j - 1; | |
} | |
$rest = $sum % 11; | |
return $numbers{13} == ($rest < 2 ? 0 : 11 - $rest); | |
}); | |
} | |
/** | |
* Register any application services. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
// | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment