fonseca / cpf_cnpj_validation
CPF and CNPJ validator for laravel applications.
Requires
- php: ^8.1
- ext-json: *
- illuminate/config: ^9.9|10.*
- illuminate/console: ^9.9|10.*
- illuminate/support: ^9.9|10.*
Requires (Dev)
- illuminate/validation: ^9.9|10.*
- leroy-merlin-br/coding-standard: v3.1.0
- mockery/mockery: ^1.6.6
- phpro/grumphp: ^1.16.0
- phpstan/phpstan: ^1.10.36
- phpunit/phpunit: ^9.6.13|10.3.5
- rector/rector: ^0.18.4
This package is auto-updated.
Last update: 2024-11-06 17:24:20 UTC
README
Introduction
This package provides a simple way to validate CPF and CNPJ for Laravel applications.
Requirements
- PHP >= 8.0.2
- Laravel >= 9.*
Installation
You can install the library via Composer:
composer require fonseca/cpf_cnpj_validation
Usage Guide
Add this code to your App\Providers\AppServiceProvider::class
.
<?php namespace App\Providers; use Fnsc\RegistrationNumber\Validator as RegistrationNumber; use Fnsc\CPF\Validator as CPF; use Fnsc\CNPJ\Validator as CNPJ; use Illuminate\Support\Facades\Validator; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { private array $rules = [ CPF::class, CNPJ::class, RegistrationNumber::class, ]; /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { $this->registerRules(); } private function registerRules(): void { foreach ($this->rules as $rule) { $alias = (new $rule)->getAlias(); Validator::extend($alias, $rule . '@passes'); } } }
Add these code to resources/lang/en/validation.php
file.
return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ ... 'cpf' => 'The :attribute is invalid.', 'cnpj' => 'The :attribute is invalid.', 'registration_number' => 'The :attribute is invalid.', ... ];
And, finally, on your FooRequest.php
file.
Here you can choose which rule will be used.
The Fnsc\RegistrationNumber\Validator as RegistrationNumber;
class made both validations, depending on the size of the string received.
The Fnsc\CPF\Validator as CPF;
made only cpf validations, and Fnsc\CNPJ\Validator as CNPJ;
made only cnpj validations.
public function rules() { return [ 'registration_number' => 'required|registration_number', 'cpf' => 'required|cpf', 'cnpj' => 'required|cnpj', ]; }
License
This package is free software distributed under the terms of the MIT license