March 25, 2023
Use Zod to Validate Forms on the Server with SvelteKit
Render issues from Zod with a Svelte component.
By Ross Robinosvelte / zod / errors
Zod is a schema validation library that works nicely with SvelteKit. It provides an easy API to quickly validate forms across an application with reusable schemas. Many popular projects use Zod to accomplish type checking at runtime. The Astro team uses Zod in their Content Collections feature to validate Markdown frontmatter. It can also be used with TypeScript or JavaScript. Here’s how to use Zod to validate forms on the server with SvelteKit.
First create a new SvelteKit project and then add Zod as a development dependency.
Consider this Zod UserSchema, it expects a user will have an email and a password. Here, Zod can also be used to transform data with the trim and toLowerCase methods. If the parse is successful, the transformed data will be available in safeParse.data.
safeParse can be utlized on any Zod schema to validate an object without creating a runtime error. For example, we could validate a user object with our UserSchema like this:
This would produce an error with an array of ZodIssue(s).
Next we can take a look at the ZodIssue object. This object is created with the safeParse method if there are any issues in the validation. After running the code above, safeParse.error.issues would contain the following ZodIssue(s) since both fields were invalid (email is missing a .com, password doesn’t contain a number).
With SvelteKit, we can implement these methods to create a form with server side validation.
The name attribute on each input element is required to get the form data in the +page.server.ts file.
Next we can create an action for our form to validate the user’s inputs on the server. If the safeParse is unsuccessful, we will return an array of ZodIssue(s) to render to the user.
If there’s any validation issues, we want to display the messages provided by our UserSchema. We can create a reusable component to render these messages in an unordered list.
In case of an invalid form, we can now utilize our ZodIssues.svelte component to display the issues.
It’s important to validate forms on the server instead of the client because anyone can modify client side code. Zod makes it easy to be consistent, you can easily reuse schemas in other actions, or utilize parts of a schema with the pick method.
Thanks for reading!…