Svelte and SvelteKit course ยท Module 13: Form Actions
Validation and Errors
In this lesson2
Server-side validation
// +page.server.js
import { fail } from '@sveltejs/kit';
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const name = data.get('name');
const strength = Number(data.get('strength'));
// Validation
if (!name || name.length < 2) {
return fail(400, {
error: 'Name must be at least 2 characters',
name,
strength
});
}
if (strength < 1 || strength > 100) {
return fail(400, {
error: 'Strength must be between 1 and 100',
name,
strength
});
}
// Success
await db.warriors.create({ name, strength });
return { success: true };
}
};<script>
let { form } = $props();
</script>
{#if form?.error}
<div class="error">{form.error}</div>
{/if}
<form method="POST">
<input
name="name"
value={form?.name ?? ''}
placeholder="Name"
/>
<input
name="strength"
type="number"
value={form?.strength ?? 50}
/>
<button>Add</button>
</form>Redirect after success
import { redirect } from '@sveltejs/kit';
export const actions = {
default: async ({ request }) => {
// ... validation and save
redirect(303, '/warriors');
}
};The redirect() function throws by itself, so you do not put throw in front of it. Status 303 tells the browser to fetch the new page with a regular GET request.
Code for this lesson: App.svelte
<script>
// Validation i errors in form actions
let formState = $state({
name: '',
email: '',
clan: ''
});
let errors = $state({});
let submitted = $state(false);
function validate() {
const newErrors = {};
if (!formState.name) {
newErrors.name = 'Name is required';
} else if (formState.name.length < 3) {
newErrors.name = 'Name must have at least 3 characters';
}
if (!formState.email) {
newErrors.email = 'Email is required';
} else if (!formState.email.includes('@')) {
newErrors.email = 'Invalid email format';
}
if (!formState.clan) {
newErrors.clan = 'Choose a clan';
}
return newErrors;
}
function handleSubmit(e) {
e.preventDefault();
errors = validate();
if (Object.keys(errors).length === 0) {
submitted = true;
}
}
</script>
<main class="validation-demo">
<h1>Form Validation</h1>
{#if submitted}
<section class="success">
<h2>Success!</h2>
<p>Welcome to the clan, {formState.name}!</p>
<button onclick={() => { submitted = false; formState = { name: '', email: '', clan: '' }; }}>
Add another
</button>
</section>
{:else}
<section class="code">
<h2>fail() - returning errors</h2>
<pre>
import {"{"} fail {"}"} from '@sveltejs/kit';
export const actions = {"{"}
default: async ({"{"} request {"}"}) => {"{"}
const data = await request.formData();
const name = data.get('name');
if (!name) {"{"}
return fail(400, {"{"}
name: 'Name required',
values: {"{"} name {"}"}
{"}"});
{"}"}
{"}"}
{"}"};
</pre>
</section>
<form onsubmit={handleSubmit}>
<div class="field" class:error={errors.name}>
<label for="name">Warrior name *</label>
<input
id="name"
bind:value={formState.name}
placeholder="np. Ragnar"
/>
{#if errors.name}
<span class="error-msg">{errors.name}</span>
{/if}
</div>
<div class="field" class:error={errors.email}>
<label for="email">Email *</label>
<input
id="email"
type="email"
bind:value={formState.email}
placeholder="ragnar@vikings.no"
/>
{#if errors.email}
<span class="error-msg">{errors.email}</span>
{/if}
</div>
<div class="field" class:error={errors.clan}>
<label for="clan">Clan *</label>
<select id="clan" bind:value={formState.clan}>
<option value="">Choose a clan...</option>
<option value="lothbrok">Lothbrok</option>
<option value="ragnarsson">Ragnarsson</option>
<option value="ironside">Ironside</option>
</select>
{#if errors.clan}
<span class="error-msg">{errors.clan}</span>
{/if}
</div>
<button type="submit">Join the clan</button>
</form>
{/if}
</main>
<style>
.validation-demo {
font-family: 'Georgia', serif;
max-width: 500px;
margin: 0 auto;
padding: 2rem;
background: #1a0f0a;
color: #e8d5b7;
min-height: 100vh;
}
h1 {
color: #d4af37;
text-align: center;
}
section {
background: rgba(212, 175, 55, 0.1);
border: 1px solid #d4af37;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
h2 {
color: #d4af37;
font-size: 1rem;
margin-top: 0;
}
pre {
background: rgba(0,0,0,0.5);
padding: 1rem;
border-radius: 4px;
font-size: 0.8rem;
overflow-x: auto;
}
.field {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: 0.25rem;
color: #d4af37;
}
input, select {
width: 100%;
padding: 0.75rem;
background: rgba(0,0,0,0.3);
border: 1px solid #3d2914;
border-radius: 4px;
color: #e8d5b7;
}
.field.error input,
.field.error select {
border-color: #ff6b6b;
}
.error-msg {
display: block;
color: #ff6b6b;
font-size: 0.85rem;
margin-top: 0.25rem;
}
button {
width: 100%;
padding: 0.75rem;
background: #3d2914;
color: #e8d5b7;
border: 1px solid #d4af37;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
.success {
text-align: center;
background: rgba(144, 238, 144, 0.1);
border-color: #90ee90;
}
.success h2 {
color: #90ee90;
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you return a validation error from a form action?