DEV Community

loading...
Cover image for Laravel 8 - Input live formatting and validation with Livewire

Laravel 8 - Input live formatting and validation with Livewire

dariusdauskurdis profile image Darius Dauskurdis ・1 min read

Sometimes for better user experience need something interactive, something that could guide user in filling form with data. Let's say dates, credit cards numbers, bank accounts, special codes and so on. Each of them has special format. For example, let's take Norwegian bank account. String format must be xxxx.xx.xxxxx
Let's add simple input and error elements in livewire blade file:

<input type="text" wire:model="bank_account" wire:change="formatBankAccount"  wire:keyup="formatBankAccount"><br />
@error('bank_account') <span class="text-red-500">{{ $message }}</span>@enderror
Enter fullscreen mode Exit fullscreen mode

With livewire actions change and keyup we will call method formatBankAccount to format our input in real time.
In Livewire component file let's add method formatBankAccount:

public function formatBankAccount(){
    $bank_account = $this->bank_account;
    $bank_account = preg_replace('/[^0-9]+/', '', $bank_account);
    $bank_account = substr($bank_account, 0, 11);
    $length = strlen($bank_account);
    $formatted = "";
    for ($i = 0; $i < $length; $i++) { 
        $formatted .= $bank_account[$i];
        if($i == 3 || $i == 5){
            $formatted .= ".";
        }
    }
    $this->bank_account = $formatted;
}
Enter fullscreen mode Exit fullscreen mode

And after submit form, we need to add validation.

$niceNames = [
    'bank_account' => 'Norwegian bank account',
];
$fields_validation = [
    'bank_account' => 'required|regex:/^[0-9]{4}\.[0-9]{2}\.[0-9]{5}$/'
];
$this->validate($fields_validation, null, $niceNames);
Enter fullscreen mode Exit fullscreen mode

So this example can be easily adjusted to any kind of string format like date xxxx-xx-xx, bank card number xxxx-xxxx-xxxx-xxxx and other.

Discussion (0)

pic
Editor guide