SvelteKit Forms 02 ๐ Validation, fail() & Named Actions โ Returning field errors cleanly and handling multiple forms per page
Robust applications require more than just accepting data; they require a rigorous process of validating that data and providing immediate, helpful feedback when it fails to meet requirements. SvelteKitโs form system handles this through a server-side validation pattern that integrates directly with the UI via the fail() helper. By returning structured error objects from the server, you allow the client to display field-level validation messages without losing the user’s previously entered input.
Furthermore, pages often demand multiple interactionsโsuch as a “Change Password” form alongside a “Delete Account” form. Named actions allow you to partition your logic on the server to handle these disparate requests within the same route, keeping your files organized and your route structure clean. This chapter explores how to orchestrate these patterns to build forms that are resilient, user-friendly, and maintainable.
Key point: The fail() helper allows you to return validation errors and status codes from server actions without triggering a redirect, enabling the form prop in your component to reactively display error messages; named actions use the ?/name convention to route specific POST requests to dedicated logic within the same server file.
Why exists
- The Data Integrity problem. Client-side validation can be bypassed; server-side validation is the only way to ensure the data reaching your database is valid.
- The State Persistence problem. Redirecting on a failed form submission clears the user’s input.
fail()returns the invalid data back to the UI, allowing you to re-populate the inputs. - The Action Namespace problem. A page might have multiple distinct forms; without named actions, all POST requests would trigger the same
defaultlogic, causing collisions. - The UX feedback problem. Users need specific information about why a form failed (e.g., “Password too short”), and returning this from the server is more secure and reliable than custom API endpoints.
- The Type Safety/Consistency problem. By grouping related actions in one
+page.server.tsfile, you can reuse shared validation schemas and helper functions easily.
a. Server-side validation and the fail() helper
When a form submission fails validation (e.g., a missing required field or a format mismatch), you should not throw an error or redirect. Instead, you return the fail() function with a status code and the error/data payload. This payload is passed to your +page.svelte component through the form prop.
// +page.server.ts
import { fail } from '@sveltejs/kit';
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const email = data.get('email');
if (!email || !email.includes('@')) {
return fail(400, { email, error: 'Invalid email address' });
}
// Proceed with database logic
}
};
Using fail() sends a response to the client with the provided HTTP status code and the data object. Because the page isn’t redirected, the user stays on the same route, and the input they provided is still available in the returned object to be re-bound to the form.
b. Partitioning logic with Named Actions
Named actions allow a single +page.server.ts to export multiple handlers. This is achieved by naming the keys in the actions object. On the client side, you target these keys by appending ?/[actionName] to the form’s action attribute.
<!-- +page.svelte -->
<form method="POST" action="?/updateProfile">...</form>
<form method="POST" action="?/updateSettings">...</form>
// +page.server.ts
export const actions = {
updateProfile: async ({ request }) => { /* Profile logic */ },
updateSettings: async ({ request }) => { /* Settings logic */ }
};
This pattern prevents “action collisions.” Each named action operates independently, allowing for granular validation rules and distinct success states for every form on the page.
c. Handling error integration in the UI
When an action returns a fail() response, it is exposed as the form prop in your page component. You can use this prop to conditionally render error messages or highlight invalid inputs.
<!-- +page.svelte -->
<script>
let { form } = $props();
</script>
<form method="POST" action="?/updateProfile">
<input name="email" value={form?.email ?? ''} />
{#if form?.error}
<p class="error">{form.error}</p>
{/if}
<button type="submit">Update</button>
</form>
By binding the value of the input to form?.email, you ensure the user’s typed input is preserved even when validation fails. This significantly improves the user experience during form correction.
Complete Example Session
// ============================================
// PART 1: THE SERVER-SIDE VALIDATION
// ============================================
import { fail } from '@sveltejs/kit';
export const actions = {
login: async ({ request }) => {
const data = await request.formData();
const user = data.get('user');
if (!user) return fail(400, { user, error: 'User is required' });
return { success: true };
},
register: async ({ request }) => {
const data = await request.formData();
const pass = data.get('pass');
if (pass.length < 8) return fail(400, { pass, error: 'Short password' });
return { success: true };
}
};
// ============================================
// PART 2: THE UI COMPONENT
// ============================================
<script>
let { form } = $props();
</script>
<form method="POST" action="?/login">
<input name="user" value={form?.user ?? ''} />
{#if form?.error}<p>{form.error}</p>{/if}
</form>
<form method="POST" action="?/register">
<input name="pass" type="password" />
{#if form?.error}<p>{form.error}</p>{/if}
</form>
This session illustrates how named actions allow multiple forms to co-exist while the fail() helper ensures that specific error messages and previous input data are routed back to the correct form.
Quick Reference
fail() Helper
| Feature | Description |
|---|---|
fail(status, data) | Returns data to UI on error |
status | HTTP status (e.g., 400) |
data | Object containing errors/inputs |
Named Actions Routing
| Action Type | Attribute Syntax |
|---|---|
| Default | action="?" |
| Named | action="?/actionName" |
| Logic Mapping | export const actions = { actionName: ... } |
Best Practices
โ Do This:
// Use fail() for all validation errors
return fail(400, { data, error: '...' }); // โ
// Always return previous input
return fail(400, { email }); // โ
// Name actions clearly
export const actions = { updateProfile: ... }; // โ
// Bind inputs to the form prop
<input value={form?.email ?? ''} /> // โ
โ Don’t Do This:
// Don't throw errors for validation
throw new Error('Invalid'); // (Page crashes) // โ
// Don't leave UI state empty on failure
// (user loses data) // โ
// Don't put business logic in +page.svelte
// (keep it server-side) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Form data lost | Not returning input in fail() | Return the input object |
| Wrong action triggered | Form action mismatch | Check action="?/name" |
| Action collision | Using default for multiple forms | Use named actions |
| State confusion | form prop from multiple forms | Use action-specific keys in form |
Real-World Examples
1. Registration validation
return fail(400, { username, error: 'Taken' });
2. Password complexity
if (p.length < 12) return fail(400, { error: 'Too weak' });
3. Named action for search
export const actions = { search: async () => { ... } }
4. Preserving old values
value={form?.email}
5. Validation helper
function validate(d) { return d ? null : 'Required'; }
6. Multi-step form
action="?/nextStep"
7. Success object
return { success: true };
8. Status codes
fail(422, { ... });
9. Server-side logs
console.error(data); return fail(500);
10. Type-safe return
return { success: true } as const;
Visual
The fail() Feedback Loop
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER SUBMIT โโโบ SERVER (fail) โโโโ VALIDATE โ
โ โ โ
โ UI (form prop) โโโโโโโโ โ
โ โ โ
โ RE-RENDER UI WITH ERROR/PREVIOUS DATA โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Named Actions Routing
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ <form action="?/A"> โโโบ actions.A โ
โ <form action="?/B"> โโโบ actions.B โ
โ โ
โ Organized, conflict-free logic. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Form Prop Persistence
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INPUT โโโบ SERVER โโโบ fail() โโโบ form prop โ
โ โ
โ [ value={form.email} ] keeps user input โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Error helper | fail(status, data) |
| Action partition | ?/actionName |
| UI integration | form prop |
| Best practice | Preserve input values |
Key takeaways:
fail()is for validation. It returns information to the client without stopping the process, allowing for rich feedback on invalid form submissions.- Named actions organize logic. They allow you to define multiple specific handlers within a single
+page.server.tsfile, preventing namespace collisions. - Preserve state on error. Always include the user’s attempted input in the
fail()data so you can re-populate the inputs in the UI. - Explicit routing. Use the
actionattribute on your<form>to map specific HTML elements to their corresponding named actions. - Server-side integrity. Never trust client-side data; always perform final validation inside your server actions before committing to your database.
Remember: Mastering the fail() helper and named actions is the key to building professional-grade forms in SvelteKit. By keeping validation server-side and using named actions to organize your handlers, you create a robust, secure, and intuitive experience that guides users through input errors without the frustration of lost data.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!