Form actions
Since this is a Svelte library, you may want to use it with the SvelteKit.
With this package you will be able to perform server-side validation of the form data
even if the user has JavaScript disabled.
Installation
Section titled “Installation”npm i @sjsf/sveltekit@nextyarn add @sjsf/sveltekit@nextpnpm add @sjsf/sveltekit@nextbun add @sjsf/sveltekit@nextExample
Section titled “Example”See details in the sections below
<script lang="ts"> import { createMeta, SvelteKitForm } from "@sjsf/sveltekit/client";
import * as defaults from "$lib/form-defaults";
import type { ActionData, PageData } from "./$types";
const meta = createMeta<ActionData, PageData>().form;</script>
<SvelteKitForm {...defaults} {meta} onSuccess={(result) => { if (result.type === "success") { console.log(result.data?.post); } }}/>import type { Actions } from "@sveltejs/kit";import type { InitialFormData } from "@sjsf/sveltekit";import { createAction } from "@sjsf/sveltekit/server";
import * as defaults from "$lib/form-defaults";import { schema, type FormValue } from "$lib/post-model";
export const load = async () => { return { // Should match action name form: { schema, initialValue: { title: "New post", content: "" } satisfies FormValue, } satisfies InitialFormData, };};
export const actions = { default: createAction( { ...defaults, name: "form", schema, sendData: true, }, ({ title, content }: FormValue) => { if (title.length > 100) { return [{ path: ["title"], message: "Title is too long" }]; } // Your logic here return { post: { id: "new-post", title, content } }; } ),} satisfies Actions;import type { FromSchema } from "json-schema-to-ts";import type { Schema } from "@sjsf/form";
export const schema = { title: "Post", type: "object", properties: { title: { title: "Title", type: "string", }, content: { title: "Content", type: "string", minLength: 5, }, }, required: ["title", "content"],} as const satisfies Schema;
export type FormValue = FromSchema<typeof schema>;Server
Section titled “Server”If you want to populate the form from the database,
you can return InitialFormData object inside the load function.
import type { InitialFormData } from "@sjsf/sveltekit";
export const load = async () => { return { // Should match action name form: { schema, initialValue: { title: "New post", content: "" } satisfies FormValue, } satisfies InitialFormData, };};You can define an action
using the createAction function.
In this case, the callback provided as the second argument
will only be called if the form data passes validation successfully.
If any errors occur during processing,
you can return an array of ValidationError objects.
Client
Section titled “Client”On the client side you can use SvelteKitForm component (see example).
Or use more flexible solution:
<script lang="ts"> import { BasicForm } from "@sjsf/form"; import { createMeta, setupSvelteKitForm } from "@sjsf/sveltekit/client";
import * as defaults from "$lib/form-defaults";
import type { ActionData, PageData } from "./$types";
const meta = createMeta<ActionData, PageData>().form; const { form } = setupSvelteKitForm(meta, { ...defaults, onSuccess: (result) => { if (result.type === "success") { console.log(result.data?.post); } }, });</script>
<BasicForm {form} method="POST" />According to Svelte documentation your form should always use POST requests.
Progressive enhancement
Section titled “Progressive enhancement”By default, the form will work even with JavaScript disabled, but you should consider the following limitations of this mode of operation:
actionshould be created withsendData: trueto persist form data between page updates- Form fields for
oneOf,anyOf,dependencies,additionalPropertiesandadditionalItemswill not expand/switch their state. - Some widgets (like multiselect, depends on the theme) may will not work, because they require
JavaScript. - Conversion from
FormDatatoJSONcan happen with data loss. This conversion relies on the field names computation algorithm and it may lead to ambiguous results if the following conditions are violated:- Id prefix and separators:
- Must be non empty, non numeric string
- Must not include each other
- Property names and keys of default object values in your schema must not contain the separators.
If they do you can change the default separators with
idSeparatorandisPseudoSeparatoroptions. Default separator values:idSeparator-.isPseudoSeparator-::
- If your schema contains
additionalProperties:- Keys of initial object values must not contain the separators.
- You may produce these checks at runtime with the
staticAnalysisand other functions from@sjsf/form/static-analysissubmodule. Functions from this submodule returns an iterable of errors, so you can:- Throw an error on the first error or list all errors (in a dev environment)
- Check if the schema and id separator is correct and save the original form data if there are errors (in a production environment)
- Do not specify
stringEmptyValuethroughextraUiOptions
- Id prefix and separators: