Skip to content
Playground

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

Terminal window
npm i @sjsf/form @sjsf/sveltekit

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}
/>

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

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

By default, the form will work even with JavaScript disabled, but you should consider the following limitations of this mode of operation:

  • validateForm2 should be called with sendData: true to persist form data between page updates
  • Form fields for oneOf, anyOf, dependencies, additionalProperties and additionalItems will not expand/switch their state.
  • Some widgets (like multiselect, depends on the theme) may will not work, because they require JavaScript.
  • Conversion from FormData to JSON can 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 idSeparator and isPseudoSeparator options. 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 additionalProperties or JavaScript is enabled but the raw form element is used (without use:form.enhance):
        • You should provide additionalPropertyKeyValidationError or additionalPropertyKeyValidator options to useSvelteKitForm for preventing the user to input invalid keys. Additional property name is invalid if:
          • additionalProperties schema is an object or an array schema and name contains idSeparator
          • additionalProperties schema is neither an object schema nor an array schema and name has a suffix consisting of a isPseudoSeparator and a keyword: key-input anyof examples help oneof
    • You may produce these checks at runtime with the staticAnalysis and other functions from @sjsf/form/static-analysis submodule. 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)