Search code examples
laravel-8laravel-livewirealpine.js

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


I have a login form with some input fields such as "email" and "password". This form is created with real-time validation by Laravel and Livewire. Until now, everything is good.

With the livewire rules I want to disable the submit button if the form fields are null or empty with Alpine.js. How do I do that?

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>

Solution

  • How about simply checking for the value iteself using blade

    <button type="submit" {{ (!is_null($email) && !empty($email) && !is_null($password) && !empty($password)) ? '' : 'disabled' }}>Login Now</button>