Handling forms in Svelte is straightforward and can be done efficiently with its reactivity and built-in form handling capabilities. Here’s a guide to creating and managing forms in Svelte, including validation and form submission.
Creating a basic form in Svelte involves using standard HTML form elements and binding them to Svelte variables using the bind
directive.
<script>
let name = '';
let email = '';
function handleSubmit() {
console.log('Name:', name);
console.log('Email:', email);
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<label for="name">Name:</label>
<input id="name" type="text" bind:value={name} />
<label for="email">Email:</label>
<input id="email" type="email" bind:value={email} />
<button type="submit">Submit</button>
</form>
Svelte doesn’t have built-in validation utilities like some frameworks, but you can easily implement validation logic within your component.
<script>
let name = '';
let email = '';
let errors = { name: '', email: '' };
function handleSubmit() {
errors = { name: '', email: '' };
if (!name) {
errors.name = 'Name is required';
}
const emailPattern = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
if (!email || !emailPattern.test(email)) {
errors.email = 'Invalid email address';
}
if (!errors.name && !errors.email) {
console.log('Form Submitted:', { name, email });
}
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<label for="name">Name:</label>
<input id="name" type="text" bind:value={name} />
{#if errors.name}
<span class="error">{errors.name}</span>
{/if}
<label for="email">Email:</label>
<input id="email" type="email" bind:value={email} />
{#if errors.email}
<span class="error">{errors.email}</span>
{/if}
<button type="submit">Submit</button>
</form>
<style>
.error {
color: red;
font-size: 0.8em;
}
</style>
To reset form fields, you can simply reassign the bound variables to their initial values.
<script>
let name = '';
let email = '';
function handleSubmit() {
console.log('Name:', name);
console.log('Email:', email);
resetForm();
}
function resetForm() {
name = '';
email = '';
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<label for="name">Name:</label>
<input id="name" type="text" bind:value={name} />
<label for="email">Email:</label>
<input id="email" type="email" bind:value={email} />
<button type="submit">Submit</button>
<button type="button" on:click={resetForm}>Reset</button>
</form>
For more advanced form handling and validation, you can use third-party libraries like svelte-forms-lib
or felte
.
svelte-forms-lib
npm install svelte-forms-lib
<script>
import { useForm } from 'svelte-forms-lib';
const { form, errors, handleSubmit, handleReset, register } = useForm({
initialValues: {
name: '',
email: '',
},
validate: values => {
const errors = {};
if (!values.name) {
errors.name = 'Name is required';
}
if (!values.email) {
errors.email = 'Email is required';
} else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(values.email)) {
errors.email = 'Invalid email address';
}
return errors;
},
onSubmit: values => {
console.log('Form Submitted:', values);
},
});
</script>
<form on:submit|preventDefault={handleSubmit}>
<label for="name">Name:</label>
<input id="name" type="text" {...register('name')} />
{#if errors.name}
<span class="error">{errors.name}</span>
{/if}
<label for="email">Email:</label>
<input id="email" type="email" {...register('email')} />
{#if errors.email}
<span class="error">{errors.email}</span>
{/if}
<button type="submit">Submit</button>
<button type="button" on:click={handleReset}>Reset</button>
</form>
<style>
.error {
color: red;
font-size: 0.8em;
}
</style>
Handling forms in Svelte is intuitive and flexible. You can start with basic form handling using built-in Svelte features and scale up to more advanced use cases with libraries like svelte-forms-lib
for comprehensive form management and validation. This approach ensures your forms are both user-friendly and maintainable.