即使填写了表格,按钮仍然禁用

button still disabled even if the form is filled

我尝试为我的表单创建一些技巧“如果表单字段为空或为空,则应禁用提交按钮”。

我通过使用 livewire 来做到这一点,但在我的例子中,即使填写了表单字段,按钮仍然被禁用。

livewire 文件:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

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 方法,因为它只会验证传递的 属性.