即使表单已填写,按钮仍然被禁用



我尝试为我的表单创建一些技巧"如果表单字段为空或空,提交按钮应该被禁用"

我通过使用livewire来做到这一点,但在我的情况下,即使表单字段被填充,按钮仍然被禁用。

livewire file:

<?php
namespace AppHttpLivewire;
use LivewireComponent;
class ExampleForm extends Component
{
public $name = '';
public $email = '';
public $password = '';

public $disabled = true;

protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
'password' => 'required|min:6',
];

public function updated($fields)
{
$this->validateOnly($fields);

if(!is_null($fields) && !empty($fields)) {
$this->$disabled = false;
} else {
$this->$disabled = true;
}
}

public function submitForm()
{
$validatedData = $this->validate();

Example::create($validatedData);
}

public function render()
{
return view('livewire.example-form');
}
}

在blade.php

<form wire:submit.prevent="submitForm">
<input type="text" wire:model="name">
@error('name') <span class="error">{{ $message }}</span> @enderror
<input type="text" wire:model="email">
@error('email') <span class="error">{{ $message }}</span> @enderror

<input type="password" wire:model="password">
@error('password') <span class="error">{{ $message }}</span> @enderror
<button type="submit" {{ $disabled ? 'disabled' : '' }}>Submit</button>
</form>

更新后的答案

根据现在的要求,只有当所有必需字段的验证通过时,disabled属性才应该设置为false。


public $disabled = true;
public function updated($fields)
{
$this->disabled = true; 
$this->validate(); // this is a blocking call
$this->disabled = false; // execution will reach this line only if all passes the validation.
}

注意,传递的$fields属性只有当前更新的属性。所以我们不能使用它来validateOnly方法,因为它只会验证传递的属性。

最新更新