How to use Superform + Yup with SvelteKit

Reading Time: 3 minutes

Using Superform with SvelteKit is really easy and a great way to progressively handle form submissions.

We'll be using Superform with Yup for validation, and TypeScript.

If you're not a TypeScript fan, just remove the typing and use .js instead of .ts for file extensions, and you should be good.

Let's go.

Requirements

Run the following in your command line at the root of your project.

and you're good, let's move onto the setup.

The Backend

We'll keep this super simple, you should be good to go in no time.

First let's create a route in your src/routes directory, make a new directory called form, and then create a +page.svelte and +page.server.ts file.

Edit your +page.server.ts file

This example is really simple, at the top we set our form schema. First we have to define it as a Yup object.

We have 2 fields; name and password, which are both required fields.

We then have to infer the type so we have a type that will allow us to access it correctly without any TypeScript warnings on the frontend.

Next we define our page data type, which will be passed to +page.svelte

Inside of our load function, we're just running a bare superValidate against the schema object.

But we could pass an object in here, if we wanted, to pre-fill the form.

This is useful when you are on a page where you are editing something, and need to load data in beforehand to populate the form.

You could pre-populate it like this.

The Frontend

Now let's hook up our +page.svelte file to this.

And that's it really.

Here were posting to the submitForm action we setup in our +page.server.ts file.

We're choosing to use the enhanced method, and also to post the form using json data.

Note how we just use bind:value here instead of using a name attribute.

Superform will know how to handle this on the server side.

When you submit the form, you should see a console message saying Success!

Wrapping up

That is really all you need to know to get started.

You don't need to use enhance if you don't want to.

You don't need to post using json data if you don't want to.

We've just chosen to do that here because it's convenient and also a good way to progressively handle forms.

If you want to handle errors when they occur, you can console log the errors value reactively.

You can then access those errors to display warnings to the user.

You can inspect the form on the backend inside of the submitForm action and operate on the form values however you need.

But this should be enough to get up and running.

Please give this a share if you found it useful 😅

Enjoyed this article? Please share it