In forms, sometimes you might want to validate only one field immediately after it is updated before the complete form submit. For example, when we have File upload field to upload images with specific maximum dimensions, it would be great to validate it right away. Let's see how to do that in Filament using the afterStateUpdated()
method.
The initial File upload field would look like this:
use Filament\Forms;use Illuminate\Validation\Rule; Forms\Components\FileUpload::make('featured_image') ->image() ->rules(Rule::dimensions()->maxWidth(600)->maxHeight(800)),
We need to call the validateOnly
Livewire method inside the afterStateUpdated
to validate this field.
use Filament\Forms;use Illuminate\Validation\Rule; Forms\Components\FileUpload::make('featured_image') ->image() ->rules(Rule::dimensions()->maxWidth(600)->maxHeight(800)) ->afterStateUpdated(function (Forms\Contracts\HasForms $livewire, Forms\Components\FileUpload $component) { $livewire->validateOnly($component->getStatePath()); }),
As you can see, I am type-hinting the $livewire
and $component
variables. For the $livewire
, the type hint shouldn't change if you do this for the form. But for the $component
, it may depend on which field you're working with.
For example, if you would want to live-validate a text input, the type-hint would be TextInput $component
:
Forms\Components\TextInput::make('title') ->minValue(2) ->required() ->live() ->afterStateUpdated(function (Forms\Contracts\HasForms $livewire, Forms\Components\TextInput $component) { $livewire->validateOnly($component->getStatePath()); }),
As you can see above, for TextInput, I also use the live()
method. It is crucial for other fields than FileUpload
. The field won't be updated instantly if you don't add that ->live()
.
Very useful. Thank you. It is working for me, but it shows an error in VS Code while coding Undefined method 'validateOnly' in red colour. Anyway it is working, but I would like not to have files showing "errors" in red in my code.
Of course I added the use Illuminate\Validation\Rule;
Any possible idea?