fonseca/cpf_cnpj_validation

CPF and CNPJ validator for laravel applications.

2.0.1 2023-10-01 04:25 UTC

This package is auto-updated.

Last update: 2024-04-09 02:26:29 UTC


README

Latest Version on Packagist Software License Total Downloads Build Status

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