Zod form validation in SvelteKit
Note
Using Zod for form validation in SvelteKit provides type-safe validation with excellent TypeScript integration. Here’s a practical approach:
In your +page.server.ts, use Zod to validate form data:
import { fail } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
default: async ({ request }) => {
const formData = await request.formData();
const data = Object.fromEntries(formData);
const result = userSchema.safeParse(data);
if (!result.success) {
return fail(400, {
errors: result.error.flatten().fieldErrors,
data
});
}
// Process valid data
console.log('Valid user data:', result.data);
return { success: true };
}
}; The flatten() method provides clean error messages that are perfect for displaying in your Svelte
components.
This approach ensures both runtime validation and compile-time type safety, making your forms robust and maintainable.