Chapter 9: Working with Forms
Forms are essential for user interaction. In this chapter, you'll learn how to create forms in Svelte with two-way binding, validation, and custom form components.
Two-Way Data Binding
Svelte's bind: directive makes form handling incredibly simple:
<script>
let name = '';
let email = '';
</script>
<input bind:value={name} placeholder="Enter name" />
<input type="email" bind:value={email} placeholder="Enter email" />
<p>Name: {name}</p>
<p>Email: {email}</p>
Form Submission
Handle form submission with the on:submit directive:
<script>
let formData = { name: '', email: '' };
function handleSubmit() {
console.log('Form submitted:', formData);
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<input bind:value={formData.name} placeholder="Name" />
<input type="email" bind:value={formData.email} placeholder="Email" />
<button type="submit">Submit</button>
</form>
Form Validation
Add validation logic to your forms:
<script>
let email = '';
let errors = {};
function validateForm() {
errors = {};
if (!email) {
errors.email = 'Email is required';
} else if (!email.includes('@')) {
errors.email = 'Invalid email format';
}
}
function handleSubmit() {
validateForm();
if (Object.keys(errors).length === 0) {
console.log('Form is valid');
}
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<input bind:value={email} placeholder="Email" />
{#if errors.email}
<p class="error">{errors.email}</p>
{/if}
<button type="submit">Submit</button>
</form>
<style>
.error { color: red; }
</style>
Checkboxes and Selects
Binding works with various input types:
<script>
let agreement = false;
let country = '';
</script>
<label>
<input type="checkbox" bind:checked={agreement} />
I agree to the terms
</label>
<select bind:value={country}>
<option value="">Select a country</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
</select>
<p>Agreement: {agreement}</p>
<p>Country: {country}</p>
Svelte makes form handling elegant and efficient!