SvelteKit
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/form @sjsf/sveltekityarn add @sjsf/form @sjsf/sveltekitpnpm add @sjsf/form @sjsf/sveltekitbun add @sjsf/form @sjsf/sveltekitExample
Section titled “Example”See details in the sections below
<script lang="ts"> import { createValidator2 } from "@sjsf/ajv8-validator"; import { theme } from "@sjsf/form/basic-theme"; import { translation } from "@sjsf/form/translations/en"; import { SvelteKitForm, createMeta } from "@sjsf/sveltekit/client";
import type { PageData, ActionData } from "./$types";
const meta = createMeta<ActionData, PageData, "form">("form");</script>
<SvelteKitForm {...theme} {meta} {translation} validator={createValidator2()} onSuccess={console.log} onFailure={console.error} onSubmitError={console.warn}/>import type { Schema } from "@sjsf/form";import { createValidator2 } from "@sjsf/ajv8-validator";import { initForm, makeFormDataParser, validateForm2,} from "@sjsf/sveltekit/server";
import type { Actions } from "./$types";
const validator = createValidator2();
const parseFormData = makeFormDataParser({ validator,});
const schema: Schema = { title: "Registration form", type: "object", required: ["firstName", "lastName"], properties: { firstName: { type: "string", title: "First name", }, lastName: { type: "string", title: "Last name", }, },};
export const load = async () => { const form = initForm({ schema, sendSchema: true }); return { form };};
export const actions = { default: async ({ request }) => { const data = await parseFormData({ schema, request, }); return { form: await validateForm2({ request, schema, validator, data, }), }; },} satisfies Actions;Server
Section titled “Server”On the server side you should implement at least one action
which will always return the result of validateForm2 function (redirect and error helpers are allowed).
If the form data is passed as FormData, you need to create a parser for it.
import type { Schema } from "@sjsf/form";import { createValidator2 } from "@sjsf/ajv8-validator";import { initForm, makeFormDataParser, validateForm2,} from "@sjsf/sveltekit/server";
import type { Actions } from "./$types";
const validator = createValidator2();
const parseFormData = makeFormDataParser({ validator,});
const schema: Schema = { title: "Registration form", type: "object", required: ["firstName", "lastName"], properties: { firstName: { type: "string", title: "First name", }, lastName: { type: "string", title: "Last name", }, },};
export const load = async () => { const form = initForm({ schema, sendSchema: true }); return { form };};
export const actions = { default: async ({ request }) => { const data = await parseFormData({ schema, request, }); return { form: await validateForm2({ request, schema, validator, data, }), }; },} satisfies Actions;If you want to populate the form from the database,
you can use the initForm function inside the load function.
import { initForm } from '@sjsf/sveltekit/server';
export const load = async () => { const data = await getData(); const form = initForm({ schema, validator, initialValue: data }); return { form };};Client
Section titled “Client”On the client side you can use SvelteKitForm component (see example).
Or use more flexible solution:
<script lang="ts"> import { RawForm, setFromContext } from "@sjsf/form"; import { createValidator2 } from "@sjsf/ajv8-validator"; import { theme } from "@sjsf/form/basic-theme"; import { translation } from "@sjsf/form/translations/en"; import { createMeta, createSvelteKitForm, createSvelteKitRequest, } from "@sjsf/sveltekit/client";
import type { PageData, ActionData } from "./$types.js";
const meta = createMeta<ActionData, PageData, "form">("form"); const request = createSvelteKitRequest(meta, { onSuccess: console.log, onFailure: console.error, }); const form = createSvelteKitForm(meta, { ...theme, validator: createValidator2(), translation, onSubmit: request.run, onSubmitError: console.warn, }); setFromContext(form.context);</script>
<RawForm {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:
validateForm2should be called 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.
- If you provide some initial value for
additionalPropertiesorJavaScriptis enabled but the rawformelement is used (withoutuse:form.enhance):- You should provide
additionalPropertyKeyValidationErrororadditionalPropertyKeyValidatoroptions touseSvelteKitFormfor preventing the user to input invalid keys. Additional property name is invalid if:additionalPropertiesschema is an object or an array schema and name containsidSeparatoradditionalPropertiesschema is neither an object schema nor an array schema and name has a suffix consisting of aisPseudoSeparatorand a keyword:key-inputanyofexampleshelponeof
- You should provide
- 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)
- Id prefix and separators: