Forms & x-model Modifiers
Handle form inputs with two‑way binding and powerful modifiers.
Handling Forms with Alpine
Alpine simplifies form management with x-model for two‑way binding and @submit.prevent for handling submissions. You can also add validation, loading states, and success messages – all without a single line of imperative JavaScript.
Complete Form Example
Code
<div x-data="{
form: { name: '', email: '' },
submitted: false,
submit() {
console.log(this.form)
this.submitted = true
}
}">
<form @submit.prevent="submit">
<input x-model="form.name" placeholder="Name" required>
<input x-model="form.email" type="email" placeholder="Email">
<button type="submit">Submit</button>
</form>
<p x-show="submitted">Thank you!</p>
</div>Form Validation
You can add simple validation using Alpine's reactive expressions. For more complex validation, you can integrate libraries like VeeValidate.
Code
<div x-data="{ email: '', isValid: true }">
<input x-model="email" @blur="isValid = email.includes('@')">
<p x-show="!isValid" class="text-red-500">Invalid email</p>
</div>x-model Modifiers
.number– converts the value to a number..trim– trims whitespace..lazy– updates data onchangeinstead ofinput..debounce.300– debounces updates by 300ms (great for search inputs).
💡 Tip
Use .debounce for live search fields to avoid making too many API calls.
Live Search
Helpful? Share this page!↑ Back to top