Tricks

Brazilian Phone Number field

Dec 5, 2022
Leandro C. Ferreira
Form builder

Building a PhoneNumber field

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

php artisan make:form-field PhoneNumber

Go to phone-number.blade.php at resources\views\forms\components\phone-number.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="14"
x-mask:dynamic="$input.length >=14 ? '(99)99999-9999' : '(99)9999-9999'" />
</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);
}

Usage

use App\Forms\Components\PhoneNumber;
 
//PhoneNumber
PhoneNumber::make('phone_number')
->rule('min:13')
->label('Telefone'),
avatar

Any clue on how to handle data that's stored without the mask? For example, if I store the phone number like "99999999999" (mobile pattern), when the field load it shows "(99)9999-9999", and it fails the validation (min:13).

The same happens with "9999999999" (landline pattern), in that case, it shows the mask properly but if I simply click to save the validation fails. Then, if I delete and -re-type the last number everything works.