I am trying to perform a real-time validation on a form using livewire 3. According to the livewire documentation, when attempting to use run-time syntaxes such as Rule::password(), you should define a rule method instead of using the #Rule. When you want to validated on realtime, you should use either wire:model.live or wire:model.blur. However, I'm unable to get the validation to run in realtime. The validation only runs when I click on the register button.
In my Register livewire component, I've defined the rules method like this
public function rules() {
return [
'name' => ['required', 'string', 'min:2'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
];
}
Then in my register method, I have made sure I called $this->validate() as shown below.
public function register(): void
{
$validated = $this->validate();
$validated['password'] = Hash::make($validated['password']);
event(new Registered($user = User::create($validated)));
auth()->login($user);
$this->redirect(RouteServiceProvider::HOME, navigate: true);
}
Also in my view, I ensure that wire:model.blur is added like this
<x-text-input wire:model.blur="name" id="name" class="block mt-1 w-full" type="text" name="name" required autofocus autocomplete="name" />
<x-input-error :messages="$errors->get('name')" class="mt-2" />
What I'm I doing wrongly?
With Livewire 3 the rules provided in function rule() are not automatically applied in real time, they are only applied when $this->validate() is called
To get around this you can use the #[Rule] attribute for validation, on each property.
Otherwise you can use the updated() method to force validation using the validations defined in rules():
public function updated($prop) {
$this->validateOnly($prop);
}