### Create New SvelteKit Project using npm Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Command to create a new SvelteKit project using npm. This is a standard way to bootstrap a new SvelteKit application. ```bash npx sv create my-app ``` -------------------------------- ### Create New SvelteKit Project using pnpm Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Command to create a new SvelteKit project using pnpm. This is an alternative package manager for creating new SvelteKit applications. ```bash pnpx sv create my-app ``` -------------------------------- ### Populate Form with Data from Database Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Shows how to populate a form with data, typically fetched from a database, using `superValidate`. The fetched data is passed as the first argument to `superValidate`, followed by the adapter. ```typescript import { error } from '@sveltejs/kit'; export const load = async ({ params }) => { // Replace with your database const user = await 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 }; }; ``` -------------------------------- ### Add Progressive Enhancement with Superforms Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md This snippet demonstrates how to integrate the `enhance` function from `superForm` into a Svelte component to enable progressive enhancement. It shows the necessary script setup and how to apply the `use:enhance` action to the form element. ```svelte
``` -------------------------------- ### Initialize Form with Yup Schema Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Illustrates form initialization with Yup validation using `superValidate` and the `yup` adapter. The schema includes default values and required fields, defined outside the `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 }; }; ``` -------------------------------- ### Initialize Form with Zod Schema (v3) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Demonstrates form initialization using Zod (v3) validation with `superValidate` and the `zod` adapter. The schema includes default values and is defined outside the `load` function. ```typescript import { superValidate } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import { z } from 'zod/v3'; // 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 }; }; ``` -------------------------------- ### Initialize Form with VineJS Schema Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Shows how to initialize a form using the VineJS validation library with `superValidate` and the `vine` adapter. It includes schema definition and default values, both defined outside the `load` function for caching. ```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 }; }; ``` -------------------------------- ### Initialize Form with Valibot Schema Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Demonstrates how to initialize a form with a Valibot schema using `superValidate` and the `valibot` adapter. The schema defines validation rules for 'name' and 'email' fields. Defaults are handled within the schema definition. ```typescript import { superValidate } from 'sveltekit-superforms'; import { valibot } from 'sveltekit-superforms/adapters'; import { object, pipe, string, optional, 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 }; }; ``` -------------------------------- ### Initialize Form with Zod Schema (v4) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Shows form initialization with Zod (v4) validation using `superValidate` and the `zod4` adapter. The schema includes default values and is defined outside the `load` function. ```typescript import { superValidate } from 'sveltekit-superforms'; import { zod4 } 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.email() }); export const load = async () => { const form = await superValidate(zod4(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Using Generic TextInput Component in a Page (Svelte) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration-v2/+page.md An example of how to use the generic `TextInput.svelte` component within a SvelteKit page. It demonstrates initializing `superForm` and passing it along with the field name to the `TextInput` component. ```svelte
``` -------------------------------- ### Create Validation Schema with VineJS Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Defines a validation schema using @vinejs/vine for form data, specifying 'name' as a string and 'email' with email format validation. ```typescript import Vine from '@vinejs/vine'; const schema = Vine.object({ name: Vine.string(), email: Vine.string().email() }); ``` -------------------------------- ### Initialize Form with Zod Mini Schema Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Illustrates form initialization with Zod Mini validation using `superValidate` and the `zod4` adapter (note: uses `zod4` adapter for Zod Mini). The schema defines default values and custom error messages. ```typescript import { superValidate } from 'sveltekit-superforms'; import { zod4 } from 'sveltekit-superforms/adapters'; import { z } from 'zod/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 }; }; ``` -------------------------------- ### Create Validation Schema with Typebox Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Generates a validation schema using Typebox for form data, specifying 'name' with a default value and 'email' with email format validation. ```typescript import Type from 'typebox'; const schema = Type.Object({ name: Type.String({ default: 'Hello world!' }), email: Type.String({ format: 'email' }) }); ``` -------------------------------- ### Create Validation Schema with Joi Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Defines a validation schema using Joi for form data, specifying 'name' as a string with a default value and 'email' as a required string with email format validation. ```javascript import Joi from 'joi'; const schema = Joi.object({ name: Joi.string().default('Hello world!'), email: Joi.string().email().required() }); ``` -------------------------------- ### Initialize Form with ArkType Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the ArkType adapter. It imports `superValidate` and the `arktype` adapter, defines a schema using `type`, and then calls `superValidate` within the load function. The schema is defined outside the load function for caching. ```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 = "Hello world!", email: 'email' }); export const load = async () => { const form = await superValidate(arktype(schema)); // Always return { form } in load functions return { form }; }; ``` -------------------------------- ### Create Validation Schema with Zod Mini Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Constructs a validation schema using Zod Mini for form data, applying a default value to 'name' and providing a custom error message for email validation. ```typescript import { z } from 'zod/mini'; const schema = z.object({ name: z._default(z.string(), 'Hello world!'), email: z.email('Invalid email') }); ``` -------------------------------- ### Initialize Form with Joi Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the Joi adapter. It imports `superValidate`, the `joi` adapter, and `Joi`. A schema is defined using Joi's object and string methods with defaults and validation rules. `superValidate` is then called within the load function. The schema is defined outside the load function. ```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 }; }; ``` -------------------------------- ### Initialize Form with Valibot Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the Valibot adapter. It imports `superValidate`, the `valibot` adapter, and Valibot schema definition functions. The schema is defined using Valibot's object, string, email, optional, pipe, and minLength functions. `superValidate` is then called within the load function. ```typescript import { superValidate } from 'sveltekit-superforms'; import { valibot } from 'sveltekit-superforms/adapters'; import { object, string, email, optional, pipe, minLength } from 'valibot'; // Schema definition would follow here, e.g.: // const schema = object({ // name: string([minLength(2)]), // email: optional(string([email()])) // }); // export const load = async () => { // const form = await superValidate(valibot(schema)); // return { form }; // }; ``` -------------------------------- ### Generic Component Script with Superforms Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration/+page.md Illustrates the script section of a generic Svelte component utilizing superforms, including type imports for Zod validation, form path leaves, and the SuperForm client. It shows the setup for `formFieldProxy`. ```svelte ``` -------------------------------- ### Post Form Data with Generic Adapter in SvelteKit Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Handles generic form data posting using superValidate with a provided adapter. It accepts a 'request' object and returns a validation failure or a success message upon successful validation. ```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!'); } }; ``` -------------------------------- ### Initialize Form with JSON Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the JSON Schema adapter. It imports `superValidate`, `JSONSchema`, and the `schemasafe` adapter. A JSON schema object defines the form structure, properties, and validation rules. The adapter must be defined before `superValidate` within 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 }; }; ``` -------------------------------- ### Configure Vite for JSON Schema Validation (TypeScript) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md This snippet shows how to configure `vite.config.ts` to include `@exodus/schemasafe` for client-side validation when using JSON Schema with Superforms. It ensures that the necessary dependency is optimized by Vite. ```typescript 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 } }); ``` -------------------------------- ### Initialize Form with Superstruct Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the Superstruct adapter. It imports `superValidate`, the `superstruct` adapter, and Superstruct functions. A schema is defined using `object`, `string`, `defaulted`, and `define` for custom validation like email. Defaults are defined outside 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 }; }; ``` -------------------------------- ### Display Form with Client-Side Binding in Svelte Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Renders an HTML form using Svelte and binds input fields to form data using superForm. It expects form data from the server and enables two-way data binding for input fields. Requires 'name' attributes on inputs unless using nested data. ```svelte
``` -------------------------------- ### Initialize Form with Effect Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the Effect adapter. It imports `superValidate` and the `effect` adapter, defines a schema using `Schema.Struct` with annotations for defaults and validation, and then calls `superValidate` in the load function. The schema is defined outside 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 }; }; ``` -------------------------------- ### Initialize Form with Typebox Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the Typebox adapter. It imports `superValidate` and the `typebox` adapter, and `Type` from Typebox. A schema is defined using `Type.Object` with properties and default values. `superValidate` is then called within the load function. The schema is defined outside the load function. ```typescript import { superValidate } from 'sveltekit-superforms'; import { typebox } from 'sveltekit-superforms/adapters'; import Type from '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 }; }; ``` -------------------------------- ### Initialize Form with Class-validator Schema in SvelteKit Load Function Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Initializes a form using `superValidate` with the Class-validator adapter. It imports `superValidate`, the `classvalidator` adapter, and validation decorators. A class defines the schema with decorators, and `superValidate` is called with the schema and default values. Defaults are defined outside 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 }; }; ``` -------------------------------- ### Create Validation Schema with Class-Validator Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Implements a validation schema using Class-Validator decorators for form data. It includes validation rules for 'name' (string, min length 2) and 'email' (string, email format). ```typescript import { IsEmail, IsString, MinLength } from 'class-validator'; class ClassValidatorSchema { @IsString() @MinLength(2) name: string = ''; @IsString() @IsEmail() email: string = ''; } export const schema = ClassValidatorSchema; ``` -------------------------------- ### Svelte Form Implementation with Error Display Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md This Svelte component demonstrates how to integrate Superforms for form handling. It uses the superForm function to manage form state, including data, errors, and constraints. The code shows how to bind input values, display validation errors conditionally, and apply HTML validation constraints. ```svelte {#if $message}

{$message}

{/if}
{#if $errors.name}{$errors.name}{/if} {#if $errors.email}{$errors.email}{/if}
``` -------------------------------- ### Form Field Proxy Limitations with Arrays and Objects Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration/+page.md Provides a TypeScript example demonstrating that `formFieldProxy` does not support arrays and objects directly in the schema path. It shows valid and invalid uses of `formFieldProxy` with a schema containing an array of objects. ```ts import { formFieldProxy } from 'sveltekit-superforms/client'; const schema = z.object({ tags: z .object({ id: z.number(), name: z.string().min(1) }) .array() }); const formData = superForm(data.form); // This won't work const tags = formFieldProxy(formData, 'tags'); // Not this either const tag = formFieldProxy(formData, 'tags[0]'); // But this will work since it's a field at the "end" of the schema const tagName = formFieldProxy(formData, 'tags[0].name'); ``` -------------------------------- ### Updated Superforms Imports (TypeScript) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration-v2/+page.md Shows the updated import paths for `sveltekit-superforms`. The `/client` and `/server` paths are no longer needed, and `SuperDebug` is now the default export. ```typescript import { superForm, superValidate, dateProxy } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import SuperDebug from 'sveltekit-superforms'; ``` -------------------------------- ### Post Form Data with Class Validator, Superstruct, ArkType, or VineJS in SvelteKit Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Handles form data posting using superValidate with adapters for class-validator, superstruct, arktype, or vinejs. It processes the 'request' object and returns either a validation error or a success message. ```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!'); } }; ``` -------------------------------- ### Create Validation Schema with Zod v3 Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Implements a validation schema using Zod v3 for form data, including a default value for 'name' and email format validation for 'email'. ```typescript import { z } from 'zod/v3'; const schema = z.object({ name: z.string().default('Hello world!'), email: z.string().email() }); ``` -------------------------------- ### Create Validation Schema with Zod v4 Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Defines a validation schema using Zod v4 for form data, specifying 'name' with a default value and 'email' using the built-in email validation. ```typescript import { z } from 'zod'; const schema = z.object({ name: z.string().default('Hello world!'), email: z.email() }); ``` -------------------------------- ### Create Validation Schema with Yup Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Creates a validation schema using Yup for form data, setting a default value for 'name' and applying email format validation to the required 'email' field. ```javascript import { object, string } from 'yup'; const schema = object({ name: string().default('Hello world!'), email: string().email().required() }); ``` -------------------------------- ### Create Validation Schema with Superstruct Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Builds a validation schema using Superstruct, including a custom 'email' validator and a default value for the 'name' field. The custom email validator checks for the presence of '@'. ```typescript 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() }); ``` -------------------------------- ### Create Validation Schema with ArkType Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Defines a validation schema using ArkType for form data, including a default value for the 'name' field. This schema is suitable for basic string and email validation. ```typescript import { type } from 'arktype'; const schema = type({ name: 'string = "Hello world!"', email: 'email' }); ``` -------------------------------- ### Special Input Formats with Proxy and Constraints (Svelte) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/concepts/client-validation/+page.md This example shows how to handle special input formats, like dates, using a proxy object and spreading constraints in Svelte. It addresses potential issues with date input and ensures the `min` attribute is correctly formatted for the date input type, overriding default constraint behavior if necessary. ```svelte ``` -------------------------------- ### Optimized Client-Side Validation with Valibot Adapter Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration-v2/+page.md Shows how to implement optimized client-side validation using the `valibotClient` adapter from `sveltekit-superforms`. This uses a minimal part of the adapter to reduce client bundle size. The same schema used on the server can be reused. ```typescript import { superForm } from 'sveltekit-superforms'; import { valibotClient } from 'sveltekit-superforms/adapters'; // Assuming 'schema' is imported from your Valibot schema file // import { schema } from './schema.js'; const { form, errors, enhance, options } = superForm(data.form, { validators: valibotClient(schema) }); ``` -------------------------------- ### Modifying use:enhance behavior with options Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/concepts/enhance/+page.md This example shows how to configure the `use:enhance` action by passing an options object to `superForm`. The options `applyAction`, `invalidateAll`, and `resetForm` allow fine-grained control over how the form interacts with SvelteKit's action system and page updates. ```typescript const { form, enhance, reset } = superForm(data.form, { applyAction: true, // or false or 'never' invalidateAll: true | false | 'force' | 'pessimistic', resetForm: true // or false }); ``` -------------------------------- ### Svelte Component for User Form Display Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/crud/+page.md This Svelte component script sets up the form handling using SvelteKit Superforms. It initializes the superForm with loaded data, manages form state, and displays status messages based on the page's status. ```svelte {#if $message}

= 400}>{$message}

{/if}

{!$form.id ? 'Create' : 'Update'} user

``` -------------------------------- ### Create Validation Schema with Valibot Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Constructs a validation schema using Valibot, applying a minimum length to 'name' and email format validation to 'email'. The 'name' field also has an optional default value. ```typescript 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()) }); ``` -------------------------------- ### Server-Side Rate Limiting with sveltekit-rate-limiter Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/rate-limiting/+page.md This snippet demonstrates how to set up and use the sveltekit-rate-limiter library to protect SvelteKit actions from excessive requests. It initializes a RateLimiter with IP and IP+User Agent limits and checks the limit on each incoming request. ```typescript import { error } from '@sveltejs/kit'; import { RateLimiter } from 'sveltekit-rate-limiter/server'; const limiter = new RateLimiter({ IP: [10, 'h'], // IP address limiter IPUA: [5, 'm'], // IP + User Agent limiter }); export const actions = { default: async (event) => { // Every call to isLimited counts as a hit towards the rate limit for the event. if (await limiter.isLimited(event)) error(429); } }; ``` -------------------------------- ### Use defaults for Initializing Forms Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration-v2/+page.md Shows how to use the renamed `defaults` function (formerly `superValidateSync`) to get default values from a schema or to supply initial data for form initialization. This is used when validation is not performed synchronously. ```typescript 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), // ... }) ``` ```typescript 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), // ... }) ``` -------------------------------- ### Generic TextInput Component (Svelte) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/migration-v2/+page.md A generic Svelte component for text input fields within a Superforms setup. It utilizes `formFieldProxy` for binding values, errors, and constraints, making it reusable for various form fields. ```svelte ``` -------------------------------- ### Load User Data for SvelteKit Page Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/crud/+page.md This TypeScript code defines the load function for a SvelteKit page. It reads user data from the database using route parameters and initializes a Superforms form. It handles 404 errors if a user is not found and returns the form and user list. ```typescript import { superValidate, message } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import { error, fail, redirect } from '@sveltejs/kit'; import { users, userId } from '$lib/users'; export const load = async ({ url, params }) => { // READ user const user = users.find((u) => u.id == params.id); if (params.id && !user) throw error(404, 'User not found.'); // If user is null, default values for the schema will be returned. const form = await superValidate(user, zod(crudSchema)); return { form, users }; }; ``` -------------------------------- ### Create Validation Schema with Effect Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Constructs a validation schema using Effect's Schema module. It includes a default value for 'name' and a custom filter for 'email' validation due to Effect's lack of built-in email parsing. ```typescript 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' } }) ) }); ``` -------------------------------- ### TypeScript Example: Using zod Adapter with Superforms Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/api/+page.md Demonstrates how to integrate a Zod schema with Superforms using the zod adapter. It shows type inference for ValidationAdapter and InferIn, highlighting the connection between the schema and the adapter's input type. ```typescript import type { Infer, InferIn } from 'sveltekit-superforms'; import { zod, zodClient } from 'sveltekit-superforms/adapters'; import { z } from 'zod'; const schema = z.object({ name: z.string().min(3) }) // Type is now ValidationAdapter, InferIn> // Which is the same as ValidationAdapter<{name: string}, {name: string}> const adapter = zod(schema); ``` -------------------------------- ### TypeScript Validation Object Structure Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md This object represents the validation result returned from the superValidate function. It includes an ID for the schema, validity status, posting status, the submitted data, and any validation errors. It's crucial for updating the form state on the client. ```typescript { id: 'a3g9kke', valid: false, posted: true, data: { name: 'Hello world!', email: '' }, errors: { email: [ 'Invalid email' ] } } ``` -------------------------------- ### Debug Form Data with SuperDebug Component in Svelte Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Integrates the SuperDebug component into a Svelte page to inspect the form data and its status. This component provides a debugging view with a copy button and status information, and it automatically updates as form fields are edited. ```svelte ``` -------------------------------- ### Simplified Superforms Imports (TypeScript) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/whats-new-v2/+page.md Demonstrates the streamlined import statements for `sveltekit-superforms`. It shows that core functionalities like `superForm` and `superValidate`, along with adapters like `zod`, can now be imported directly from the main package, and `SuperDebug` is available as the default export, simplifying project setup. ```typescript import { superForm, superValidate, dateProxy } from 'sveltekit-superforms'; import { zod } from 'sveltekit-superforms/adapters'; import SuperDebug from 'sveltekit-superforms'; // Example usage: // const { form, fields } = superForm(data, { // validators: zod(schema) // }); ``` -------------------------------- ### Create Validation Schema with JSON Schema Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/get-started/[...lib]/+page.md Specifies a validation schema using JSON Schema format for form data. It includes type definitions, default values, required fields, and email format validation. Note: $ref properties are not supported. ```typescript 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 ``` -------------------------------- ### Single File Input with on:input (Svelte) Source: https://github.com/ciscoheat/superforms-web/blob/main/src/routes/concepts/files/+page.md This Svelte component example shows how to handle file uploads using an `on:input` event handler on the file input element. It manually assigns the selected file to the form data and includes client-side validation with Zod, displaying any errors. ```svelte
($form.image = e.currentTarget.files?.item(0) as File)} /> {#if $errors.image}{$errors.image}{/if}
> The `as File` casting is needed since `null` is the value for "no file", so be aware that `$form.image` may be `null` even though the schema type says otherwise. If you want the upload to be optional, set the field to `nullable` and it will be type-safe. ```