Alpine.js 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);
}
}
Why complicate things? When using Livewire you should put front-end logic in Livewire components. But why do you care about disabled state when it will not be submitted due to failed validation?
Create a boolean to make sure of the disable state
public $isDisabled = true;
// To validate an input field after every update, we can use Livewire's updated hook
public function updated()
{
if(!is_null($email) && !empty($email) && !is_null($password) && !empty($password)) {
$isDisabled = false;
} else {
$isDisabled = true;
}
}