Svelte · Middle · Question 36 of 75

How do you validate a form in a SvelteKit action and return errors?

import { fail } from "@sveltejs/kit";

export const actions = {
  default: async ({ request }) => {
    const data = await request.formData();
    const email = data.get("email");
    if (!email) return fail(400, { email, missing: true });
    // ...
  },
};

Explanation

Returning the submitted values lets the form keep what the user typed.

Further reading

Problem with a question

Svelte · Middle · question 36

Test yourself

Take the Svelte · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz