Chapter 9: Working with Forms
bind: directive eliminates repetitive onChange boilerplate while keeping validation, accessibility, and submission states explicit.
Two-Way Data Binding
In plain HTML, inputs hold their own DOM state. Using bind:value={variable} creates a two-way link: typing in the input updates your JavaScript variable, and assigning to that variable in code updates the input. For type="number" or type="range" inputs, Svelte automatically coerces the bound value to a JavaScript number instead of a string. Always pair inputs with an explicit <label for="..."> for accessibility:
<script>
let name = '';
let email = '';
</script>
<label for="user-name">Name</label>
<input id="user-name" bind:value={name} placeholder="Enter name" />
<label for="user-email">Email</label>
<input id="user-email" type="email" bind:value={email} placeholder="Enter email" />
<p>Preview: {name || 'Anonymous'} ({email || 'no email'})</p>
Form Submission
Wrap related inputs in a semantic <form> element and attach on:submit|preventDefault={handleSubmit}. Using a real <form> lets users submit by pressing Enter inside any text field, while |preventDefault stops the browser from reloading the page. Track an explicit submitting flag to prevent duplicate requests:
<script>
let formData = { name: '', email: '' };
let submitting = false;
async function handleSubmit() {
submitting = true;
try {
await saveUser(formData);
} finally {
submitting = false;
}
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<input bind:value={formData.name} placeholder="Name" required />
<input type="email" bind:value={formData.email} placeholder="Email" required />
<button type="submit" disabled={submitting}>
{submitting ? 'Saving...' : 'Submit'}
</button>
</form>
Form Validation
Store validation errors in an object keyed by field name so each input can display its own inline message and set aria-invalid for screen readers. Validate on submit (and optionally on blur after a field is touched) rather than showing errors before the user finishes typing:
<script>
let email = '';
let errors = {};
function validateForm() {
const next = {};
if (!email.trim()) {
next.email = 'Email is required.';
} else if (!email.includes('@')) {
next.email = 'Enter a valid email address.';
}
errors = next;
return Object.keys(next).length === 0;
}
function handleSubmit() {
if (validateForm()) {
console.log('Valid submission:', email);
}
}
</script>
<form on:submit|preventDefault={handleSubmit} novalidate>
<input
type="email"
bind:value={email}
aria-invalid={Boolean(errors.email)}
placeholder="Email"
/>
{#if errors.email}
<p class="error" role="alert">{errors.email}</p>
{/if}
<button type="submit">Submit</button>
</form>
<style>
.error { color: #f87171; }
</style>
Checkboxes and Selects
Different form controls bind to different properties: checkboxes use bind:checked for booleans, radio groups use bind:group, and <select> dropdowns use bind:value:
<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} | Country: {country || 'None'}</p>
Practice: Build a registration form with name, email, country select, and terms checkbox, validating all fields on submit and disabling the submit button until the request resolves.