| | |

SvelteKit Forms 02 ๐Ÿ“ Validation, fail() & Named Actions โ€” Returning field errors cleanly and handling multiple forms per page

โฑ๏ธ Estimated read: 7 min | |

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 default logic, 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.ts file, 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

FeatureDescription
fail(status, data)Returns data to UI on error
statusHTTP status (e.g., 400)
dataObject containing errors/inputs

Named Actions Routing

Action TypeAttribute Syntax
Defaultaction="?"
Namedaction="?/actionName"
Logic Mappingexport 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

PitfallWhy It HappensFix
Form data lostNot returning input in fail()Return the input object
Wrong action triggeredForm action mismatchCheck action="?/name"
Action collisionUsing default for multiple formsUse named actions
State confusionform prop from multiple formsUse 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

ItemValue
Error helperfail(status, data)
Action partition?/actionName
UI integrationform prop
Best practicePreserve 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.ts file, 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 action attribute 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.

Was this helpful?


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!