-
-
Notifications
You must be signed in to change notification settings - Fork 73
There is only one Page
and ActionData
on a page, so multiple forms on the same page can cause trouble since it's hard to know which form updated page
. An example is if you have a login form in the navigation that will be present on every page.
Fortunately sveltekit-superforms has a simple solution for this, by setting options.applyAction
to false
, which will prevent it from updating Page
and ActionData
. If you want to make it completely self-contained, set options.invalidateAll
to false
as well.
See this wiki entry for a list of default values, used when data for a schema field is missing.
Yes, you can set a default
schema value to anything you'd like it to be. For example with the classic "agree to terms" checkbox:
const schema = z.object({
age: z.number().positive().default(NaN),
agree: z.literal(true).default(false as true)
})
This looks strange, but will ensure that an age must be selected and the agree checkbox is unchecked as default, and will only accept true as a value. Just note that you will bypass the type system with this, so the default value will not correspond to the data type, but this will usually not be a problem since form.valid
will be false
if the default values are posted as-is, and that should be the main determinant whether the data is trustworthy.
When you start to configure the library to suit your stack, it's recommended to create an object with default options that you will refer to instead:
import { superForm } from 'sveltekit-superforms/client';
import type { AnyZodObject } from 'zod';
export function yourSuperForm<T extends AnyZodObject>(
...params: Parameters<typeof superForm<T>>
) {
return superForm(params[0], {
// Your defaults here
errorSelector: '.has-error',
delayMs: 300,
...params[1]
});
}
Currently, file uploads are not handled with sveltekit-superforms
. The recommended way to do it is to grab the FormData
and extract the files from there, after validation:
export const actions = {
default: async ({ request }) => {
const formData = await request.formData();
const form = await superValidate(formData, schema);
if (!form.valid) return fail(400, { form });
const file = formData.get('file');
if (file instanceof File) {
// Do something with the file.
}
return { form };
}
} satisfies Actions;