表单字段为空时如何禁用提交按钮?

How to disable submit button whenever the form fields are empty?

我有一个登录表单,其中包含一些输入字段,例如“电子邮件”和“密码”。此表单由 Laravel 和 Livewire 通过实时验证创建。到目前为止,一切都很好。

使用 livewire 规则,如果表单字段为 null 或为空 Alpine.js,我想禁用提交按钮。我该怎么做?

app\Http\Livewire\LoginForm

class LoginForm extends Component
{
    public $email = '';
    public $password = '';

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

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

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

        User::create($validatedData);
    }
}

LoginForm Component

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

    <input type="password" wire:model="password" class="form-control">
    @error('password') <span class="error">{{ $message }}</span> @enderror

    <button type="submit">Login Now</button>
</form>

在您的组件中,您可以使用单独的 属性 public bool $canBeSubmitted 来保持按钮的 enabled/disabled 状态。

class LoginForm extends Component
{
    public $email = '';
    public $password = '';

    /**
     * Toggle disabled state of submit button
     */
    public bool $canBeSubmitted = false;

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

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

        // Setting $canBeSubmitted to true/false 
    }

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

        User::create($validatedData);
    }
}
<form wire:submit.prevent="saveUser">
    <!-- inputs -->

    <button type="submit" {{ !empty($canBeSubmitted)) ? '' : 'disabled' }}>Login Now</button>
</form>

AlpineJS 和 Livewire

要从 AlpineJS 和 Livewire 访问 canBeSubmitted 属性,您可以使用 entangled feature.

来自文档:

Livewire has an incredibly powerful feature called "entangle" that allows you to "entangle" a Livewire and Alpine property together. With entanglement, when one value changes, the other will also be changed.

使用 blade

简单地检查值 iteself 怎么样?
<button type="submit" {{ (!is_null($email) && !empty($email) && !is_null($password) && !empty($password)) ? '' : 'disabled' }}>Login Now</button>