Tricks

Brazilian CPF/CNPJ field

Jan 3, 2023
Leandro C. Ferreira
Form builder

Building a CpfCnpj field

Let's create our CpfCnpj field. You may use the following command:

php artisan make:form-field CpfCnpj

Go to cpf-cnpj.blade.php at resources\views\forms\components\cpf-cnpj.blade.php and add the following:

<x-forms::field-wrapper :id="$getId()" :label="$getLabel()" :label-sr-only="$isLabelHidden()" :helper-text="$getHelperText()" :hint="$getHint()"
:hint-icon="$getHintIcon()" :required="$isRequired()" :state-path="$getStatePath()">
<div x-data="{ state: $wire.entangle('{{ $getStatePath() }}') }">
<input {!! $isDisabled() ? 'disabled' : null !!}
class="block w-full transition duration-75 border-gray-300 rounded-lg shadow-sm focus:border-primary-500 focus:ring-1 focus:ring-inset focus:ring-primary-500 disabled:opacity-70 dark:bg-gray-700 dark:text-white dark:focus:border-primary-500 dark:border-gray-600"
wire:model.defer="{{ $getStatePath() }}" placeholder="" type="text" maxlength="18"
x-mask:dynamic="$input.length >14 ? '99.999.999/9999-99' : '999.999.999-99'" />
</div>
</x-forms::field-wrapper>

Go to AppServiceProvider at app\Providers\AppServiceProvider.php and add the following:

use Filament\Facades\Filament;
 
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Filament::registerScripts([
'https://unpkg.com/@alpinejs/[email protected]/dist/cdn.min.js',
], true);
}

Validation

To get started with laravellegends/pt-br-validator, you can install it using the command:

composer require laravellegends/pt-br-validator

Usage

You can validate the input by passing cpf_ou_cnpj validation rule:

use App\Forms\Components\CpfCnpj;
 
//CpfCnpj
CpfCnpj::make('document')
->rule('cpf_ou_cnpj')
->required(),

No comments yet…