### Initializing Form with VineJS Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This example shows how to integrate sveltekit-superforms with the VineJS validation library. It defines a schema and separate default values, then passes both to the vine adapter when calling superValidate in the SvelteKit load function to set up the form. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { vine } from 'sveltekit-superforms/adapters'; import Vine from '@vinejs/vine'; // Define outside the load function so the adapter can be cached const schema = Vine.object({ name: Vine.string(), email: Vine.string().email() }); // Defaults should also be defined outside the load function const defaults = { name: 'Hello world!', email: '' }; export const load = async () => { const form = await superValidate(vine(schema, { defaults })); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Defining a Superform Validation Schema Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This collection of snippets illustrates how to create a validation schema for a Superform, specifically defining `name` and `email` fields. Examples are provided for various popular validation libraries, showcasing their specific syntax and features for schema definition, which is a prerequisite for creating a Superform. ```ts import { type } from 'arktype'; const schema = type({ name: 'string', email: 'email' }); ``` ```ts import { IsEmail, IsString, MinLength } from 'class-validator'; class ClassValidatorSchema { @IsString() @MinLength(2) name: string = ''; @IsString() @IsEmail() email: string = ''; } export const schema = ClassValidatorSchema; ``` ```ts import { Schema } from 'effect'; // effect deliberately does not provide email parsing out of the box // https://github.com/Effect-TS/schema/issues/294 // here is a simple email regex that does the job const emailRegex = /^[^@]+@[^@]+\.[^@]+$/; const schema = Schema.Struct({ name: Schema.String.annotations({ default: 'Hello world!' }), email: Schema.String.pipe( Schema.filter((s) => emailRegex.test(s) || 'must be a valid email', { jsonSchema: { format: 'email' } }) ) }); ``` ```ts import Joi from 'joi'; const schema = Joi.object({ name: Joi.string().default('Hello world!'), email: Joi.string().email().required() }); ``` ```ts import type { JSONSchema } from 'sveltekit-superforms'; export const schema = { type: 'object', properties: { name: { type: 'string', minLength: 2, default: 'Hello world!' }, email: { type: 'string', format: 'email' } }, required: ['name', 'email'], additionalProperties: false, $schema: 'http://json-schema.org/draft-07/schema#' } as const satisfies JSONSchema; // Define as const to get type inference ``` ```ts import { object, string, defaulted, define } from 'superstruct'; const email = () => define('email', (value) => String(value).includes('@')); export const schema = object({ name: defaulted(string(), 'Hello world!'), email: email() }); ``` ```ts import { Type } from '@sinclair/typebox'; const schema = Type.Object({ name: Type.String({ default: 'Hello world!' }), email: Type.String({ format: 'email' }) }); ``` ```ts import { object, string, email, optional, pipe, minLength } from 'valibot'; export const schema = object({ name: pipe(optional(string(), 'Hello world!'), minLength(2)), email: pipe(string(), email()) }); ``` ```ts import Vine from '@vinejs/vine'; const schema = Vine.object({ name: Vine.string(), email: Vine.string().email() }); ``` ```ts import { object, string } from 'yup'; const schema = object({ name: string().default('Hello world!'), email: string().email().required() }); ``` ```ts import { z } from 'zod'; const schema = z.object({ name: z.string().default('Hello world!'), email: z.string().email() }); ``` ```ts import { z } from 'zod/v4'; const schema = z.object({ name: z.string().default('Hello world!'), email: z.email() }); ``` ```ts import { z } from 'zod/v4-mini'; const schema = z.object({ name: z._default(z.string(), 'Hello world!'), email: z.email('Invalid email') }); ``` -------------------------------- ### Setting up Superforms Development Environment with npm Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-contributing-+page.md This snippet provides the commands to set up the Superforms development environment using npm. It installs project dependencies and then starts the development server, allowing contributors to run and test the project locally. ```Shell npm install npm run dev ``` -------------------------------- ### Setting up Superforms Development Environment with pnpm Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-contributing-+page.md This snippet provides the commands to set up the Superforms development environment using pnpm. It installs project dependencies and then starts the development server, offering an alternative package manager for contributors. ```Shell pnpm install pnpm dev ``` -------------------------------- ### Initializing Form with Zod Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This example demonstrates integrating sveltekit-superforms with the Zod validation library. It defines a Zod schema for 'name' and 'email' fields, including a default value for 'name', and then uses the zod adapter to initialize the form within a SvelteKit load function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import { z } from 'zod'; // Define outside the load function so the adapter can be cached const schema = z.object({ name: z.string().default('Hello world!'), email: z.string().email() }); export const load = async () => { const form = await superValidate(zod(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Initializing Form with Zod Mini Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This example demonstrates integrating sveltekit-superforms with the Zod v4-mini validation library. It defines a Zod v4-mini schema for 'name' and 'email' fields, using z._default for default values and custom error messages, and then initializes the form using the zod4 adapter within a SvelteKit load function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { zod4 } from 'sveltekit-superforms/adapters'; import { z } from 'zod/v4-mini'; // Define outside the load function so the adapter can be cached const schema = z.object({ name: z._default(z.string(), 'Hello world!'), email: z.email('Invalid email') }); export const load = async () => { const form = await superValidate(zod4(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Updating Superforms Imports (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This example demonstrates the simplified import paths for `sveltekit-superforms`. The `/client` and `/server` paths are no longer required for most imports, improving consistency. Adapters are now imported from `sveltekit-superforms/adapters`, and `SuperDebug` is the default export. ```typescript import { superForm, superValidate, dateProxy } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import SuperDebug from 'sveltekit-superforms'; ``` -------------------------------- ### Initializing a New SvelteKit Project Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This section provides commands to create a new SvelteKit application from scratch, offering options for different package managers (npm, pnpm, yarn). The command `npx sv create my-app` is used to scaffold the project, setting up the basic directory structure and dependencies. ```npm npx sv create my-app ``` -------------------------------- ### Initializing Form with Joi in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet demonstrates initializing a SvelteKit Superform with Joi for schema validation. It defines a Joi object schema with default values and validation rules for name and email, then uses `superValidate` with the `joi` adapter within the `load` function to create the form object. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { joi } from 'sveltekit-superforms/adapters'; import Joi from 'joi'; // Define outside the load function so the adapter can be cached const schema = Joi.object({ name: Joi.string().default('Hello world!'), email: Joi.string().email().required() }); export const load = async () => { const form = await superValidate(joi(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Displaying a SvelteKit Superform on the Client Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This Svelte component snippet demonstrates how to display a form on the client-side using data passed from `+page.server.ts`. It uses `bind:value` for two-way data binding with input fields and emphasizes the importance of the `name` attribute for inputs and having only one `superForm` instance per form. ```Svelte
``` -------------------------------- ### Configuring Vite for JSON Schema Client Validation Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet demonstrates how to modify the `vite.config.ts` file to enable client-side validation when using JSON Schema with Superforms. It involves adding `@exodus/schemasafe` to the `optimizeDeps.include` array to ensure proper bundling and functionality. ```ts import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [sveltekit()], optimizeDeps: { include: ['@exodus/schemasafe'] // Add this to make client-side validation work } }); ``` -------------------------------- ### Initializing Form with Valibot Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet demonstrates how to initialize a form using sveltekit-superforms with the Valibot validation library. It defines a schema for 'name' and 'email' fields, including default values and validation rules, and then uses superValidate within a SvelteKit load function to create the form object. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { valibot } from 'sveltekit-superforms/adapters'; import { object, string, email, optional, pipe, minLength } from 'valibot'; // Define outside the load function so the adapter can be cached const schema = object({ name: pipe(optional(string(), 'Hello world!'), minLength(2)), email: pipe(string(), email()) }); export const load = async () => { const form = await superValidate(valibot(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Initializing Form with Class-validator in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet shows how to integrate Class-validator with SvelteKit Superforms. It defines a class with `class-validator` decorators for name and email validation, instantiates it as the schema, and initializes the form using `superValidate` and the `classvalidator` adapter in the `load` function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { classvalidator } from 'sveltekit-superforms/adapters'; import { IsEmail, IsString, MinLength } from 'class-validator'; // Define outside the load function so the adapter can be cached class ClassValidatorSchema { @IsString() @MinLength(2) name: string = ''; @IsString() @IsEmail() email: string = ''; } const schema = ClassValidatorSchema; // Defaults should also be defined outside the load function const defaults = new schema(); export const load = async () => { // class-validator requires explicit default values for now const form = await superValidate(classvalidator(schema, { defaults })); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Initializing Form with Superstruct in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet illustrates integrating Superstruct for schema validation with SvelteKit Superforms. It defines a Superstruct object schema with a custom email type and default values, then initializes the form using `superValidate` with the `superstruct` adapter in the `load` function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { superstruct } from 'sveltekit-superforms/adapters'; import { object, string, defaulted, define } from 'superstruct'; const email = () => define('email', (value) => String(value).includes('@')); // Define outside the load function so the adapter can be cached const schema = object({ name: defaulted(string(), 'Hello world!'), email: email() }); // Defaults should also be defined outside the load function const defaults = { name: 'Hello world!', email: '' }; export const load = async () => { const form = await superValidate(superstruct(schema, { defaults })); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Initializing Form with TypeBox in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet demonstrates how to use TypeBox for schema validation with SvelteKit Superforms. It defines a TypeBox object schema for name and email, including a default value for name and format for email, then initializes the form using `superValidate` with the `typebox` adapter in the `load` function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { typebox } from 'sveltekit-superforms/adapters'; import { Type } from '@sinclair/typebox'; // Define outside the load function so the adapter can be cached const schema = Type.Object({ name: Type.String({ default: 'Hello world!' }), email: Type.String({ format: 'email' }) }); export const load = async () => { const form = await superValidate(typebox(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Initializing Form with Yup Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet illustrates how to use sveltekit-superforms with the Yup validation library. It defines a Yup schema with default values and validation rules for 'name' and 'email' fields, then initializes the form using the yup adapter within a SvelteKit load function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { yup } from 'sveltekit-superforms/adapters'; import { object, string } from 'yup'; // Define outside the load function so the adapter can be cached const schema = object({ name: string().default('Hello world!'), email: string().email().required() }); export const load = async () => { const form = await superValidate(yup(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Using intProxy with SvelteKit Superforms (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-api-+page.md This snippet provides an example of how to use intProxy to create a string store for an integer field within a SuperForm. It shows the basic setup with superForm and then how to initialize intProxy with the form object and the field name. ```TypeScript import { superForm, intProxy } from 'sveltekit-superforms'; let { data } = $props(); const { form } = superForm(data.form); const proxy = intProxy(form, 'field', { options }); ``` -------------------------------- ### Populating SvelteKit Superform from Database Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet shows how to populate a sveltekit-superforms form with data retrieved from a database within a SvelteKit load function. It fetches user data based on URL parameters, handles a 'not found' error, and then passes the retrieved data along with a schema adapter to superValidate to pre-fill the form. ```TypeScript import { error } from '@sveltejs/kit'; export const load = async ({ params }) => { // Replace with your database const user = db.users.findUnique({ where: { id: params.id } }); if (!user) error(404, 'Not found'); const form = await superValidate(user, your_adapter(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Initializing Form with Effect in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet illustrates how to use Effect for schema validation with SvelteKit Superforms. It defines an Effect `Schema.Struct` for name and email, including a custom email validation pipe, and then initializes the form using `superValidate` with the `effect` adapter in the `load` function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { effect } from 'sveltekit-superforms/adapters'; import { Schema } from 'effect'; const emailRegex = /^[^@]+@[^@]+.[^@]+$/; const schema = Schema.Struct({ name: Schema.String.annotations({ default: 'Hello world!' }), email: Schema.String.pipe( Schema.filter((s) => emailRegex.test(s) || 'must be a valid email', { jsonSchema: { format: 'email' } }) ) }); export const load = async () => { const form = await superValidate(effect(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Using Defaults for Schema-Only Initialization in SuperForm (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This example demonstrates the new `defaults` function, replacing `superValidateSync`, for initializing a form with default values directly from a schema without requiring validation. It's suitable for client-side form setup. ```ts import { defaults } from 'sveltekit-superforms' // Getting the default values from the schema: const { form, errors, enhance } = superForm(defaults(zod(schema)), { SPA: true, validators: zod(schema), // ... }) ``` -------------------------------- ### Debugging SvelteKit Superform with SuperDebug Component Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This Svelte component snippet shows how to integrate the `SuperDebug` component to inspect the state of a `sveltekit-superforms` form. By binding `data={$form}`, it provides real-time visibility into form data, validation status, and other internal states, aiding in debugging client-side form interactions. ```Svelte ``` -------------------------------- ### Enabling Progressive Enhancement with SvelteKit use:enhance Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet demonstrates how to apply the `use:enhance` action, returned from `superForm`, directly to a `
` element in SvelteKit. This enables progressive enhancement, preventing full page reloads on submission and unlocking client-side features like validation, events, loading spinners, and auto error focus. The action takes no arguments, with events used for hooking into SvelteKit's `use:enhance` parameters. ```Svelte ``` -------------------------------- ### Initializing Form with JSON Schema in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet shows how to use a standard JSON Schema for form validation with SvelteKit Superforms. It defines a JSON Schema object with properties, required fields, and default values, then initializes the form using `superValidate` with the `schemasafe` adapter in the `load` function. ```TypeScript import { superValidate, type JSONSchema } from 'sveltekit-superforms'; import { schemasafe } from 'sveltekit-superforms/adapters'; export const schema = { type: 'object', properties: { name: { type: 'string', minLength: 2, default: 'Hello world!' }, email: { type: 'string', format: 'email' } }, required: ['name', 'email'], additionalProperties: false, $schema: 'http://json-schema.org/draft-07/schema#' } as const satisfies JSONSchema; export const load = async () => { // The adapter must be defined before superValidate for JSON Schema. const adapter = schemasafe(schema); const form = await superValidate(request, adapter); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Handling Form Post with Various Adapters in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This TypeScript snippet demonstrates a SvelteKit form action for POST requests, utilizing `sveltekit-superforms` with various schema adapters (Class Validator, Superstruct, Arktype, VineJS). It validates `FormData` using `superValidate` and a custom `your_adapter`. If validation fails, it returns a 400 status; otherwise, it returns the form with a success message, highlighting the necessity of returning the `form` object. ```TypeScript import { message } from 'sveltekit-superforms'; import { fail } from '@sveltejs/kit'; export const actions = { default: async ({ request }) => { const form = await superValidate(request, your_adapter(schema, { defaults })); console.log(form); if (!form.valid) { // Return { form } and things will just work. return fail(400, { form }); } // TODO: Do something with the validated form.data // Return the form with a status message return message(form, 'Form posted successfully!'); } }; ``` -------------------------------- ### Initializing Form with Arktype in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet demonstrates how to initialize a SvelteKit Superform using Arktype for schema validation. It defines an Arktype schema for name and email fields, sets default values, and then uses `superValidate` with the `arktype` adapter within the `load` function to create the form object. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { arktype } from 'sveltekit-superforms/adapters'; import { type } from 'arktype'; // Define outside the load function so the adapter can be cached const schema = type({ name: 'string', email: 'email' }); // Defaults should also be defined outside the load function const defaults = { name: 'Hello world!', email: '' }; export const load = async () => { // Arktype requires explicit default values for now const form = await superValidate(arktype(schema, { defaults })); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Handling Form Post with Generic Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This TypeScript snippet provides a general SvelteKit form action for POST requests. It uses `sveltekit-superforms` with a generic `your_adapter` to validate `FormData`. It checks `form.valid` and returns a 400 error if validation fails, otherwise it returns a success message along with the `form` object, which is crucial for client-side updates. ```TypeScript import { message } from 'sveltekit-superforms'; import { fail } from '@sveltejs/kit'; export const actions = { default: async ({ request }) => { const form = await superValidate(request, your_adapter(schema)); console.log(form); if (!form.valid) { // Return { form } and things will just work. return fail(400, { form }); } // TODO: Do something with the validated form.data // Return the form with a status message return message(form, 'Form posted successfully!'); } }; ``` -------------------------------- ### Initializing Form with Zod v4 Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This snippet shows how to use sveltekit-superforms with the Zod v4 validation library. It defines a Zod v4 schema for 'name' and 'email' fields, including a default value for 'name', and then initializes the form using the zod4 adapter within a SvelteKit load function. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { zod4 } from 'sveltekit-superforms/adapters'; import { z } from 'zod/v4'; // Define outside the load function so the adapter can be cached const schema = z.object({ name: z.string().default('Hello world!'), email: z.email() }); export const load = async () => { const form = await superValidate(zod4(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Using superValidate with Arktype Adapter and Defaults Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This example shows how to use `superValidate` with an Arktype schema, which requires providing default values due to its introspection limitations. The schema and defaults are defined at the module top-level for caching. The `defaults` object is passed as an option to the `arktype` adapter. ```TypeScript import { type } from 'arktype'; // Arktype schema, powerful stuff const schema = type({ name: 'string', email: 'email', tags: '(string>=2)[]>=3', score: 'integer>=0' }); const defaults = { name: '', email: '', tags: [], score: 0 }; export const load = async () => { const form = await superValidate(arktype(schema, { defaults })); return { form }; }; ``` -------------------------------- ### Handling Form Post with JSON Schema Adapter in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This TypeScript snippet defines a SvelteKit form action for handling POST requests. It uses `sveltekit-superforms` with a `schemasafe` adapter for JSON Schema validation. The `superValidate` function processes the request, and if validation fails, it returns a 400 status with the form data. On success, it returns the form with a status message. It emphasizes always returning the `form` object. ```TypeScript import { message } from 'sveltekit-superforms'; import { fail } from '@sveltejs/kit'; export const actions = { default: async ({ request }) => { // The adapter must be defined before superValidate for JSON Schema. const adapter = schemasafe(schema); const form = await superValidate(request, adapter); console.log(form); if (!form.valid) { // Return { form } and things will just work. return fail(400, { form }); } // TODO: Do something with the validated form.data // Return the form with a status message return message(form, 'Form posted successfully!'); } }; ``` -------------------------------- ### Client-Side Validation with Deprecated Superform Client Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This example demonstrates using the deprecated `superformClient` for client-side validation. It requires importing `Infer` for correct typing and manually handling type checking and validation logic within the validator function. The input parameter can now be `undefined`, necessitating explicit checks. ```TypeScript import type { Infer } from 'sveltekit-superforms'; import type { schema } from './schema.js'; import { superformClient } from 'sveltekit-superforms/adapters'; const { form, errors, enhance } = superForm(data.form, { validators: superformClient>({ name: (name?) => { if(!name || name.length < 2) return 'Name must be at least two characters' } }) }); ``` -------------------------------- ### Updating sveltekit-superforms Version in package.json (JSON) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This snippet shows how to update the `sveltekit-superforms` dependency in your `package.json` file to version `^1.0.0` for general use, or `^1.1.2` if you are using Svelte 4, to ensure compatibility with the latest Superforms features. ```json { "devDependencies": { "sveltekit-superforms": "^1.0.0" } } ``` -------------------------------- ### Composing Multiple Data Sources for SuperDebug in Svelte Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-super-debug-+page.md This example demonstrates how to debug multiple stores or objects simultaneously by passing them as a single object to the `data` prop. This allows for a consolidated view of related debugging information, such as form data and associated errors. ```svelte ``` -------------------------------- ### Displaying Default SuperDebug Output in Svelte Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-super-debug-+page.md This example demonstrates the default output of the `SuperDebug` component when provided with the `$form` data. It shows the basic rendering without any specific customizations, displaying the form data and page status. ```svelte ``` -------------------------------- ### Displaying Form Validation Errors in Svelte Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This Svelte component demonstrates how to display validation errors and status messages from `superForm` on the client. It binds input values to `$form` and conditionally renders error messages using `$errors` and `$message` stores. The `aria-invalid` attribute is used for accessibility and automatic error focusing, while `$constraints` enables built-in browser validation. ```svelte {#if $message}

{$message}

{/if} {#if $errors.name}{$errors.name}{/if} {#if $errors.email}{$errors.email}{/if}
``` -------------------------------- ### Debugging Svelte Stores Directly with SuperDebug Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-super-debug-+page.md This example shows that `SuperDebug` can directly accept and display the contents of a Svelte store (e.g., `form`). This simplifies debugging by allowing direct inspection of store values without needing to dereference them. ```svelte ``` -------------------------------- ### Client-Side Validation with Valibot Adapter Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This snippet illustrates how to implement client-side validation using the `valibotClient` adapter. It imports the client-specific adapter and the schema, then passes `valibotClient(schema)` to the `validators` option of `superForm`. This approach minimizes bundle size by using a smaller part of the adapter. ```TypeScript import { valibotClient } from 'sveltekit-superforms/adapters'; import { schema } from './schema.js'; const { form, errors, enhance, options } = superForm(data.form, { validators: valibotClient(schema) }); ``` -------------------------------- ### HTML Date Input with SvelteKit Superforms Proxy (Svelte) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-api-+page.md An example of an HTML `input` element of type `date` bound to a proxied date store (`$date`), illustrating how to integrate proxied values with Svelte's `bind:value` directive for seamless form input management. ```Svelte ``` -------------------------------- ### Using Defaults with Initial Data for SuperForm Initialization (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This snippet shows how to use the `defaults` function to initialize a Superform with partial initial data alongside the schema. The provided initial data will not be validated, making it useful for pre-filling forms. ```ts import { defaults } from 'sveltekit-superforms' // Supplying initial data (can be partial, won't be validated) const initialData = { name: 'New user' } const { form, errors, enhance } = superForm(defaults(initialData, zod(schema)), { SPA: true, validators: zod(schema), // ... }) ``` -------------------------------- ### Updating allErrors Signature - Diff Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This diff shows the change in the `allErrors` signature, transitioning from an array of paths to a single path string and grouping messages into an array. This simplifies error grouping. ```Diff - { path: string[]; message: string[] } + { path: string; messages: string[] } ``` -------------------------------- ### Svelte FieldProxy Basic Usage Example Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-components-+page.md This Svelte snippet demonstrates the basic usage of a field proxy (`$name`) to interact with a specific part of the `$form` store. Updates to the proxy reflect in the main form store and vice versa, providing a convenient way to manage individual form fields. ```svelte
Name: {$name}
``` -------------------------------- ### Displaying Separate allErrors Messages - Svelte Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This Svelte snippet shows an alternative way to display error messages from the `$allErrors` store, rendering each individual message separately for a given path. It uses nested loops for this purpose. ```Svelte {#if $allErrors.length}
    {#each $allErrors as error} {#each error.messages as message}
  • {error.path}: {message}.
  • {/each} {/each}
{/if} ``` -------------------------------- ### Updating SuperValidate Type Parameters with Infer (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This snippet demonstrates how to correctly use `Infer` to wrap schema parameters when calling `superValidate` or defining `SuperValidated` types. It shows the updated syntax for type inference with `sveltekit-superforms`. ```ts import type { Infer } from 'sveltekit-superforms' import { zod } from 'sveltekit-superforms/adapters' import { schema } from './schema.js' type Message = { status: 'success' | 'failure', text: string } const form = await superValidate, Message>(zod(schema)); ``` -------------------------------- ### Displaying Grouped allErrors Messages - Svelte Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This Svelte snippet demonstrates how to iterate over the `$allErrors` store to display error messages grouped by their respective paths. It checks if `$allErrors` has length before rendering a list. ```Svelte {#if $allErrors.length}
    {#each $allErrors as error}
  • {error.path}: {error.messages.join('. ')}.
  • {/each}
{/if} ``` -------------------------------- ### Manually Specifying Form IDs for Identical Schemas in SvelteKit Superforms Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-whats-new-v1-+page.md This example illustrates the exception where manual `id` specification is still required. If multiple forms on the same page utilize the exact same schema content, a unique `id` must be provided to differentiate them, ensuring correct form handling. ```ts const form1 = await superValidate(schema, { id: 'form1' }); const form2 = await superValidate(schema, { id: 'form2' }); return { form1, form2 }; ``` -------------------------------- ### Implementing Catch-All Schema with Zod and Superforms (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-concepts-strict-mode-+page.md This example illustrates how to use Zod's `catchall` method to validate any unknown fields in a schema, ensuring they conform to a specified type (e.g., integers). It demonstrates integrating this schema with `superValidate` in a SvelteKit action, handling form validation, and accessing typed data for both known and catch-all fields. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import { z } from 'zod'; const schema = z.object({ name: z.string().min(1) }) .catchall(z.number().int()); // All unknown fields should be integers export const actions = { default: async ({ request }) => { const form = await superValidate(request, zod(schema)); if (!form.valid) { return fail(400, { form }); } // Typed as string, as expected console.log(form.data.name); // All other keys are typed as number console.log(form.data.first, form.data.second); return { form }; } }; ``` -------------------------------- ### Defining SuperValidated Type with Infer in Svelte Props (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This example illustrates how to define a `SuperValidated` type for Svelte component props, ensuring proper type inference for the schema using `Infer` from `sveltekit-superforms`. ```ts import type { LoginSchema } from '$lib/schemas'; import type { Infer } from 'sveltekit-superforms' let { data } : { data: SuperValidated> } = $props(); ``` -------------------------------- ### Creating SvelteKit Project with pnpx Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-crud-+page.md This command initializes a new SvelteKit project named 'sf-crud' using 'pnpx' (pnpm's npx equivalent). It serves the same purpose as the 'npx' command, allowing users to choose their preferred package manager. Users should select 'Skeleton project' and 'Typescript syntax' when prompted. ```shell pnpx sv create sf-crud ``` -------------------------------- ### Creating a Generic TextInput Svelte Component with Superforms (Svelte) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This Svelte component demonstrates how to create a reusable `TextInput` field that integrates seamlessly with Superforms. It uses `formFieldProxy` to bind the input's value, display errors, and apply constraints, making it type-safe and generic for various form schemas. ```svelte ``` -------------------------------- ### Creating SvelteKit Project with npx Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-crud-+page.md This command initializes a new SvelteKit project named 'sf-crud' using 'npx'. It's the first step to set up the development environment for the Superforms CRUD tutorial. Users should select 'Skeleton project' and 'Typescript syntax' when prompted. ```shell npx sv create sf-crud ``` -------------------------------- ### Using superValidate with Zod Adapter Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md This snippet demonstrates how to use `superValidate` in Superforms v2 with a Zod schema. It requires importing `superValidate` and the `zod` adapter, then wrapping the Zod schema with the adapter before passing it to `superValidate`. This is the standard way to integrate Zod for server-side validation. ```TypeScript import { superValidate } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; const form = await superValidate(zod(schema)); ``` -------------------------------- ### Defining Zod Schema with Refine for setError (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This TypeScript snippet demonstrates how to define a Zod schema with a `refine` method to implement custom validation logic, such as password confirmation. Errors generated by `refine` will be available on the client as `$errors._errors` and are automatically managed during client-side validation. ```typescript const schema = z .object({ password: z.string().min(8), confirmPassword: z.string() }) .refine((data) => password == confirmPassword, `Passwords doesn't match.`); ``` -------------------------------- ### Using intProxy with SvelteKit Superforms Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-concepts-proxy-objects-+page.md This example illustrates how to use `intProxy` to convert a form field (e.g., `id`) to and from an integer. It shows two ways to initialize the proxy: using the `form` store directly or using the entire `superForm` object, which allows setting the `taint` option to prevent form tainting on updates. ```TypeScript import { superForm, intProxy } from 'sveltekit-superforms'; // Assume the following schema: // { id: number } const superform = superForm(data.form); const { form, errors, enhance } = superform; // Returns a Writable const idProxy = intProxy(form, 'id'); // Use the whole superForm object to prevent tainting const idProxy2 = intProxy(superform, 'id', { taint: false }); ``` -------------------------------- ### Defining User Schema and Mock Database in TypeScript Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-crud-+page.md This TypeScript snippet defines a 'userSchema' using Zod for data validation, ensuring 'id', 'name', and 'email' conform to specified types and formats. It also includes a 'userId' utility function and a mock 'users' array to simulate a database, providing initial data for testing CRUD operations. This setup is crucial for backend data integrity. ```typescript import { z } from 'zod'; // See https://zod.dev/?id=primitives for schema syntax export const userSchema = z.object({ id: z.string().regex(/^\\d+$/), name: z.string().min(2), email: z.string().email() }); type UserDB = z.infer[]; // Let's worry about id collisions later export const userId = () => String(Math.random()).slice(2); // A simple user "database" export const users: UserDB = [ { id: userId(), name: 'Important Customer', email: 'important@example.com' }, { id: userId(), name: 'Super Customer', email: 'super@example.com' } ]; ``` -------------------------------- ### Migrating validate from Array to String FieldPath (Diff) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This diff snippet demonstrates the migration of the `validate` function's field path argument from an array-based syntax (e.g., `['tags', i, 'name']`) to a new string accessor syntax (e.g., ``tags[${i}].name``). This change applies to `setError`, `validate`, and proxy functions for simplified field referencing. ```diff const { form, enhance, validate } = superForm(data.form) - validate(['tags', i, 'name'], { update: false }); + validate(`tags[${i}].name`, { update: false }); ``` -------------------------------- ### Removing Manual Form IDs with use:enhance in SvelteKit Superforms Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-whats-new-v1-+page.md This snippet demonstrates how Superforms 1.0, when used with `use:enhance`, automatically assigns unique IDs to forms, eliminating the need for manual `id` specification for forms with different schemas. This simplifies form setup and reduces boilerplate. ```diff const loginForm = await superValidate(loginSchema, { - id: 'loginForm' }); const registerForm = await superValidate(registerSchema, { - id: 'registerForm' }); return { loginForm, registerForm } ``` -------------------------------- ### Checking Form Tainted Status with `isTainted` (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-v2-+page.md The `superForm.isTainted` method provides a reliable way to check if any part of the form has been modified from its original state. This example shows how to initialize `superForm` and then use `isTainted()` to check the entire form or `isTainted('fieldName')` to check a specific field's tainted status. ```typescript const { form, enhance, isTainted } = superForm(form.data); // Check the whole form if(isTainted()) // Check a part of the form if(isTainted('name')) ``` -------------------------------- ### Handling Nested Data with TextField Component (Svelte) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-components-+page.md This example demonstrates how to use the generic `TextField` component to manage nested data, specifically an array of tags. It iterates over the `$form.tags` array using Svelte's `{#each}` block, creating a `TextField` for each tag's name, showcasing dynamic form field generation for complex data structures. ```Svelte

Tags

{#each $form.tags as _, i} {/each} ``` -------------------------------- ### Using message for Persistent Form-Level Errors (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-migration-+page.md This TypeScript example illustrates how to use the `message` function to set a form-level error that persists across client-side validations until the next form submission. This is useful for messages that should remain visible regardless of subsequent client-side schema validation results, unlike `setError` which can conflict with client-side validation. ```typescript const form = await superValidate(request, zod(schema)); if (!form.valid) return fail(400, { form }); if (form.data.password != form.data.confirmPassword) { // Stays until form is posted again, regardless of client-side validation return message(form, `Passwords doesn't match`, { status: 400 }); } ``` -------------------------------- ### Simplified Import Paths for SvelteKit Superforms v2 (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-whats-new-v2-+page.md This TypeScript snippet illustrates the streamlined import structure in Superforms v2. It shows how core functionalities like `superForm`, `superValidate`, and `dateProxy` are now imported directly from `sveltekit-superforms`, while adapters (e.g., `zod`) are imported from a dedicated `adapters` subpath. `SuperDebug` is also simplified as the default export. ```ts import { superForm, superValidate, dateProxy } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import SuperDebug from 'sveltekit-superforms'; ``` -------------------------------- ### Understanding SuperValidate Return Object (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-get-started-[...lib]-+page.md This TypeScript snippet illustrates the structure of the validation object returned by `superValidate` after a form submission. It includes properties like `id`, `valid`, `posted`, `data`, and `errors`, which are crucial for updating the form state on the client. The `errors` property specifically highlights validation failures, such as an invalid email. ```ts { id: 'a3g9kke', valid: false, posted: true, data: { name: 'Hello world!', email: '' }, errors: { email: [ 'Invalid email' ] } } ``` -------------------------------- ### Initializing String Proxy with SvelteKit Superforms (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-api-+page.md Demonstrates how to initialize a `stringProxy` for a schema field, connecting it to a `superForm`. This creates a string store for a string field, useful for converting empty strings to `null` or `undefined` before schema validation. ```TypeScript import { superForm, stringProxy } from 'sveltekit-superforms'; let { data } = $props(); const { form } = superForm(data.form); const proxy = stringProxy(form, 'field', { options }); ``` -------------------------------- ### Initializing Number Proxy with SvelteKit Superforms (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-api-+page.md Demonstrates how to initialize a `numberProxy` for a schema field, linking it to a `superForm` instance. This creates a string store for a number field, useful for handling numeric inputs and their string representations. ```TypeScript import { superForm, numberProxy } from 'sveltekit-superforms'; let { data } = $props(); const { form } = superForm(data.form); const proxy = numberProxy(form, 'field', { options }); ``` -------------------------------- ### Loading Data with Promise for SuperDebug in SvelteKit Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-super-debug-+page.md This SvelteKit `+page.ts` snippet demonstrates how to fetch data asynchronously using a promise and return it from the `load` function. The `promiseProduct` will then be available to the Svelte component for debugging with `SuperDebug`. ```ts export const load = (async ({ fetch }) => { const promiseProduct = fetch('https://dummyjson.com/products/1') .then(response => response.json()) return { promiseProduct } }) ``` -------------------------------- ### Initializing Date Proxy with SvelteKit Superforms (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-api-+page.md Illustrates how to initialize a `dateProxy` for a schema field, linking it to a `superForm`. This creates a string store for a Date field, enabling control over the date's string format for various display and submission needs. ```TypeScript import { superForm, dateProxy } from 'sveltekit-superforms'; let { data } = $props(); const { form } = superForm(data.form); const proxy = dateProxy(form, 'field', { options }); ``` -------------------------------- ### Initializing Boolean Proxy with SvelteKit Superforms (TypeScript) Source: https://github.com/speedysh/superform-docs/blob/main/docs/routes-api-+page.md Shows how to initialize a `booleanProxy` for a schema field, connecting it to a `superForm`. This creates a string store for a boolean field, allowing customization of the string representation for `true`. ```TypeScript import { superForm, booleanProxy } from 'sveltekit-superforms'; let { data } = $props(); const { form } = superForm(data.form); const proxy = booleanProxy(form, 'field', { options }); ```