Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Formsnap
https://www.formsnap.dev/docs
Admin
Accessible and powerful form components for SvelteKit.
Tokens:
18,457
Snippets:
82
Trust Score:
6.4
Update:
1 year ago
Context
Chat
Benchmark
88
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Formsnap and Dependencies Source: https://www.formsnap.dev/docs/quick-start This snippet demonstrates how to install Formsnap, Superforms, and Zod using npm. Superforms is required as Formsnap is built on top of it, and Zod is used for schema validation. ```Shell npm install formsnap sveltekit-superforms zod ``` -------------------------------- ### Setup Formsnap Form in Svelte Page Component Source: https://www.formsnap.dev/docs/quick-start This Svelte snippet demonstrates how to initialize a Superform in a SvelteKit page component using `superForm`. It enables client-side validation with `zodClient` and applies progressive enhancement to the HTML form using the `enhance` function. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { Field } from "formsnap"; import { zodClient } from "sveltekit-superforms/adapters"; import { allergies, schema, themes } from "./schema.js"; import SuperDebug from "sveltekit-superforms"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema) }); const { form: formData, enhance } = form; </script> <form method="POST" use:enhance> <!-- ... --> </form> <SuperDebug data={$formData} /> ``` -------------------------------- ### Initialize a Formsnap Field Component in Svelte Source: https://www.formsnap.dev/docs/quick-start This Svelte snippet demonstrates the initial setup of a form field using the `Field` component from Formsnap. It integrates with `sveltekit-superforms` to manage form state and validation, passing the `form` instance and the `name` of the schema property to establish the field's context. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { Field } from "formsnap"; import { zodClient } from "sveltekit-superforms/adapters"; import { allergies, schema, themes } from "./schema.js"; import SuperDebug from "sveltekit-superforms"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData, enhance } = form; </script> <form method="POST" use:enhance> <Field {form} name="email"> <!-- ... --> </Field> </form> <SuperDebug data={$formData} /> ``` -------------------------------- ### Build a Complete Formsnap Field with Control, Label, Description, and Errors in Svelte Source: https://www.formsnap.dev/docs/quick-start This Svelte snippet expands on the basic `Field` setup by incorporating `Control`, `Label`, `Description`, and `FieldErrors` components. It illustrates how to create an accessible input with an associated label, provide contextual information, and display validation errors, all while maintaining synchronization with the form data. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { Field, Control, Label, Description, FieldErrors } from "formsnap"; import { zodClient } from "sveltekit-superforms/adapters"; import { allergies, schema, themes } from "./schema.js"; import SuperDebug from "sveltekit-superforms"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData, enhance } = form; </script> <form method="POST" use:enhance> <Field {form} name="email"> <Control> {#snippet children({ props })} <Label>Email</Label> <input {...props} type="email" bind:value={$formData.email} /> {/snippet} </Control> <Description>Use your company email if you have one.</Description> <FieldErrors /> </Field> </form> <SuperDebug data={$formData} /> ``` -------------------------------- ### SvelteKit ElementField Usage Example Source: https://www.formsnap.dev/docs/components/element-field Demonstrates how to use the ElementField component within a SvelteKit Superforms setup to manage a dynamic list of URLs. This example shows how to iterate over an array in the form data and create a separate ElementField for each item, enabling individual error display and form submission. ```Svelte <script lang="ts"> import { ElementField, FieldErrors, Control, Label, Fieldset, Description } from "formsnap"; import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { z } from "zod"; const schema = z.object({ urls: z.array(z.string().url()).min(2).default(["", ""]), }); let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData, enhance } = form; </script> <form use:enhance method="POST"> <Fieldset {form} name="urls"> <Legend>Enter your URLS</Legend> {#each $formData.urls as _, i} <ElementField {form} name="urls[{i}]"> <Control> {#snippet children({ props })} <input type="url" bind:value={$formData.urls[i]} {...props} /> {/snippet} </Control> <FieldErrors /> </ElementField> {/each} <Description>Your URLs will be displayed on your public profile.</Description> <FieldErrors /> </Fieldset> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Return Superform from SvelteKit Load Function Source: https://www.formsnap.dev/docs/quick-start This TypeScript snippet shows how to return a Superform instance from a SvelteKit `+page.server.ts` load function. It uses `superValidate` with the Zod adapter to prepare the form data for the page component, ensuring seamless merging of PageData and ActionData. ```TypeScript import type { PageServerLoad } from "./$types"; import { schema } from "./schema"; import { superValidate } from "sveltekit-superforms"; import { zod } from "sveltekit-superforms/adapters"; export const load: PageServerLoad = async () => { return { form: await superValidate(zod(schema)) }; }; ``` -------------------------------- ### Implement a Settings Form with Formsnap and SvelteKit Superforms Source: https://www.formsnap.dev/docs/quick-start This Svelte component demonstrates how to construct a comprehensive settings form using Formsnap components (Field, Control, Label, Description, FieldErrors, Fieldset, Legend) in conjunction with SvelteKit Superforms for form handling and validation. It showcases various input types including text, textarea, select, radio, and checkbox, and illustrates how to group related fields using Fieldset for improved accessibility and organization. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { Field, Control, Label, Description, FieldErrors, Fieldset, Legend } from "formsnap"; import { zodClient } from "sveltekit-superforms/adapters"; import { allergies, schema, themes } from "./schema.js"; import SuperDebug from "sveltekit-superforms"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData, enhance } = form; </script> <form use:enhance class="mx-auto flex max-w-md flex-col" method="POST"> <Field {form} name="email"> <Control> {#snippet children({ props })} <Label>Email</Label> <input {...props} type="email" bind:value={$formData.email} /> {/snippet} </Control> <Description>Company email is preferred</Description> <FieldErrors /> </Field> <Field {form} name="bio"> <Control> {#snippet children({ props })} <Label>Bio</Label> <textarea {...props} bind:value={$formData.bio} /> {/snippet} </Control> <Description>Tell us a bit about yourself.</Description> <FieldErrors /> </Field> <Field {form} name="language"> <Control> {#snippet children({ props })} <Label>Language</Label> <select {...props} bind:value={$formData.language}> <option value="fr">French</option> <option value="es">Spanish</option> <option value="en">English</option> </select> {/snippet} </Control> <Description>Help us address you properly.</Description> <FieldErrors /> </Field> <Fieldset {form} name="theme"> <Legend>Select your theme</Legend> {#each themes as theme} <Control> {#snippet children({ props })} <Label>{theme}</Label> <input {...props} type="radio" value={theme} bind:group={$formData.theme} /> {/snippet} </Control> {/each} <Description>We prefer dark mode, but the choice is yours.</Description> <FieldErrors /> </Fieldset> <Field {form} name="marketingEmails"> <Control> {#snippet children({ props })} <input {...props} type="checkbox" bind:checked={$formData.marketingEmails} /> <Label>I want to receive marketing emails</Label> {/snippet} </Control> <Description>Stay up to date with our latest news and offers.</Description> <FieldErrors /> </Field> <Fieldset {form} name="allergies"> <Legend>Food allergies</Legend> {#each allergies as allergy} <Control> {#snippet children({ props })} <input {...props} type="checkbox" bind:group={$formData.allergies} value={allergy} /> <Label>{allergy}</Label> {/snippet} </Control> {/each} <Description>When we provide lunch, we'll accommodate your needs.</Description> <FieldErrors /> </Fieldset> <button>Submit</button> </form> <SuperDebug data={$formData} /> ``` -------------------------------- ### Svelte: Apply CSS Framework Classes to Formsnap Components Source: https://www.formsnap.dev/docs/styling This Svelte code example illustrates how to integrate Formsnap components with popular CSS frameworks like TailwindCSS or UnoCSS. By passing framework-specific utility classes directly to the `class` prop of Formsnap components, developers can quickly apply styles. The example shows styling a `Label` component with `text-black` and `hover:text-orange-500` classes. ```Svelte <script lang="ts"> import { Label } from "formsnap"; </script> <form> <!-- ... --> <Label class="text-black hover:text-orange-500">First Name</Label> <!-- ... --> </form> ``` -------------------------------- ### Build a Custom Svelte Wrapper for Formsnap Control Source: https://www.formsnap.dev/docs/components/control This example illustrates how to create a reusable `CustomControl.svelte` component that wraps Formsnap's `Control` and `Label` components. This approach promotes consistent UI/UX by automatically including a label and applying common styling, such as wrapping content in a `div`. It demonstrates how to forward props and manage component composition effectively. ```Svelte <script lang="ts"> import { Control, Label } from "formsnap"; import type { ComponentProps } from "svelte"; let { label, // Rename the children prop to childrenProp to avoid // conflicts with the Control component children: childrenProp, ...restProps }: ComponentProps<typeof Control> & { label: string; } = $props(); </script> <Control {...restProps}> {#snippet children({ props })} <div class="flex flex-col gap-2"> <Label>{label}</Label> <!-- Forward the props to the children snippet --> {@render childrenProp({ props })} </div> {/snippet} </Control> ``` -------------------------------- ### Svelte FieldErrors Basic Usage Example Source: https://www.formsnap.dev/docs/components/field-errors This example demonstrates the straightforward integration of the FieldErrors component within a Formsnap Field. It shows how FieldErrors automatically displays validation messages for the associated input field without requiring explicit error handling logic. ```HTML <Field {form} name="name"> <Control> {#snippet children({ props })} <Label>Name</Label> <input type="text" {...props} /> {/snippet} </Control> <FieldErrors /> </Field> ``` -------------------------------- ### Define Zod Schema for Form Data Source: https://www.formsnap.dev/docs/quick-start This TypeScript snippet defines a Zod schema for a settings form, including fields for email, bio, theme, language, marketing emails, and allergies. This schema is used for both client-side and server-side validation of form data. ```TypeScript import { z } from "zod"; export const themes = ["light", "dark"] as const; export const languages = ["en", "es", "fr"] as const; export const allergies = ["peanuts", "dairy", "gluten", "soy", "shellfish"] as const; export const schema = z.object({ email: z.string().email("Please enter a valid email."), bio: z.string().optional(), theme: z.enum(themes).default("light"), language: z.enum(languages).default("en"), marketingEmails: z.boolean().default(true), allergies: z.array(z.enum(allergies)) }); ``` -------------------------------- ### Svelte: Integrate Custom Component with Formsnap Control Source: https://www.formsnap.dev/docs/composition/use-form-control This Svelte example shows how to integrate the custom `LabelInput` component, which uses `useFormControl` internally, within a Formsnap `Field` and `Control` structure. It highlights the seamless composition of custom elements into the Formsnap form system. ```Svelte <Field {form} name="email"> <Control> <LabelInput label="Email address" /> </Control> </Field> ``` -------------------------------- ### Update Formsnap Form Field Access with useFormField Source: https://www.formsnap.dev/docs/v2-migration-guide This section outlines the migration from `getFormField` (v1) to `useFormField` (v2) for accessing form field state. `useFormField` now provides reactive getters instead of stores, requiring a different access pattern for field properties. ```TypeScript (v1) <script lang="ts"> import { getFormField } from "formsnap"; const { form, errors, tainted, constraints } = getFormField(); </script> Errors for this field: {$errors} Constraints for this field: {$constraints} Is this field tainted? {$tainted} ``` ```TypeScript (v2) <script lang="ts"> import { useFormField } from "formsnap"; const field = useFormField(); </script> Errors for this field: {field.errors} Constraints for this field: {field.constraints} Is this field tainted? {field.tainted} ``` -------------------------------- ### Setup Svelte Form with Superforms, Bits-UI Select, and Formsnap Source: https://www.formsnap.dev/docs/recipes/bits-ui-select This snippet demonstrates how to create a multi-select form field for 'favorite colors' using SvelteKit Superforms for data binding and validation (with Zod), Bits-UI for the accessible Select component, and Formsnap for managing form fields, labels, and errors. It requires 'sveltekit-superforms', 'sveltekit-superforms/adapters', 'bits-ui', and 'formsnap' dependencies. The code takes initial form data and a schema as input, renders a form with a multi-select dropdown, and handles form submission. The `props` from Formsnap's `Control` are applied to `Select.Trigger` for accessibility, and `props.name` is applied to `Select.Root` to render a hidden input for form submission. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { Select } from "bits-ui"; import { Field, Control, Label, FieldErrors, Description } from "formsnap"; import { schema, colors } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData } = form; const selectedColors = $derived( $formData.colors.length ? $formData.colors.map((c) => colors[c]).join(",") : "Select colors" ); </script> <form method="POST" use:form.enhance> <Field {form} name="colors"> <Control> {#snippet children({ props })} <Label>Favorite colors</Label> <Select.Root type="multiple" bind:value={$formData.colors} name={props.name}> <Select.Trigger {...props}> {selectedColors} </Select.Trigger> <Select.Content> {#each Object.entries(colors) as [value, label]} <Select.Item {value} {label} /> {/each} </Select.Content> </Select.Root> {# /snippet} </Control> <Description>We'll use these colors to customize your experience.</Description> <FieldErrors /> </Field> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Update Formsnap Form Control Access with useFormControl Source: https://www.formsnap.dev/docs/v2-migration-guide This section describes the migration from `getFormControl` (v1) to `useFormControl` (v2) for hooking into the closest parent `Control` component's state. `useFormControl` now returns reactive getters, changing the access pattern for control properties. ```TypeScript (v1) <script lang="ts"> import { getFormControl } from "formsnap"; import { MyLabel, MyInput } from "$lib/components"; export let label: string; const { labelAttrs, attrs } = getFormControl(); </script> <MyLabel {...$labelAttrs}> {label} </MyLabel> <MyInput {...$attrs} /> ``` ```TypeScript (v2) <script lang="ts"> import { useFormControl } from "formsnap"; import { MyLabel, MyInput } from "$lib/components"; let { label }: { label: string } = $props(); const control = useFormControl(); </script> <MyLabel {...control.labelProps}> {label} </MyLabel> <MyInput {...control.props} /> ``` -------------------------------- ### Implement Formsnap Control with Svelte Input Source: https://www.formsnap.dev/docs/components/control This snippet demonstrates the basic integration of Formsnap's `Control` component with a standard Svelte input field. It utilizes a Svelte snippet to pass essential accessibility and form-related props to the input, ensuring proper association with its label. The example also shows how to bind the input's value to a Svelte store for data management. ```Svelte <Control> {#snippet children({ props })} <input type="text" {...props} bind:value={$formData.name} /> {/snippet} </Control> ``` -------------------------------- ### Initialize SuperForm for Client-Side Validation in Svelte Source: https://www.formsnap.dev/docs/recipes/checkbox-groups This snippet demonstrates how to initialize `sveltekit-superforms` in a Svelte component. It uses the `superForm` function to bind form data received from the server and integrates `zodClient` for efficient client-side validation. This setup makes the form reactive and provides immediate user feedback. ```typescript import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import SuperDebug from "sveltekit-superforms"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData } = form; ``` -------------------------------- ### Migrate Formsnap `asChild` prop to `child` snippet in Svelte Source: https://www.formsnap.dev/docs/v2-migration-guide Formsnap v2 replaces the `asChild` prop with the more flexible `child` snippet pattern for components that render an HTML element. This change requires updating component usage to wrap custom elements within a `{#snippet child({ props })}` block, spreading the `props` object onto your element. This new pattern allows for greater control over the rendered output while maintaining component functionality. ```Svelte <!-- This could apply to any component that rendered an HTML element --> <Label asChild let:labelAttrs> <label {...labelAttrs}>Name</label> </Label> ``` ```Svelte <!-- This applies to any component that renders an HTML element --> <Label> {#snippet child({ props })} <label {...props}>Name</label> {/snippet} </Label> ``` -------------------------------- ### Update Formsnap Control Component for Svelte Snippets Source: https://www.formsnap.dev/docs/v2-migration-guide This section details the migration of the Formsnap `Control` component from using `attrs` slot props (v1) to `children` snippet props (v2). This change is necessary due to Svelte's deprecation of slot props in favor of snippets for attribute passing. ```Svelte (v1) <Control let:attrs> <input type="text" {...attrs} bind:value={$formData.name} /> </Control> ``` ```Svelte (v2) <Control> {#snippet children({ props })} <input type="text" {...props} bind:value={$formData.name} /> {/snippet} </Control> ``` -------------------------------- ### Add/Remove Dynamic URL Fields with Formsnap in Svelte Source: https://www.formsnap.dev/docs/recipes/dynamic-fields This snippet extends the previous example by adding functionality to dynamically add and remove URL fields. It integrates SvelteKit Superforms and Formsnap components, demonstrating how to update the `$formData.urls` array and include buttons for adding new entries and removing existing ones. ```svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { Fieldset, Legend, ElementField, Control, Label, FieldErrors, Description, } from "formsnap"; import { schema } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData } = form; function removeUrlByIndex(index: number) { $formData.urls = $formData.urls.filter((_, i) => i !== index); } function addUrl() { $formData.urls = [...$formData.urls, ""]; } </script> <form use:form.enhance method="POST"> <Fieldset {form} name="urls"> <Legend>Public URLs</Legend> {#each $formData.urls as _, i} <ElementField {form} name="urls[{i}]"> <Control> {#snippet children({ props })} <Label class="sr-only">URL {i + 1}</Label> <input type="url" {...props} bind:value={$formData.urls[i]} /> <button type="button" onclick={() => removeUrlByIndex(i)}> Remove URL </button> {#/snippet} </Control> <Description class="sr-only"> This URL will be publicly available on your profile. </Description> <FieldErrors /> </ElementField> {#/each} <FieldErrors /> <button type="button" onclick={addUrl}>Add URL</button> </Fieldset> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Update Formsnap element references from `el` to `ref` in Svelte Source: https://www.formsnap.dev/docs/v2-migration-guide Formsnap v2 updates how element references are obtained, replacing the `el` prop with the `$bindable` `ref` prop. This change requires updating `bind:el` to `bind:ref` and initializing the bound variable with `$state<HTMLElement | null>(null)`. The `ref` prop provides a direct reference to the underlying HTML element rendered by the component. ```Svelte <script lang="ts"> import { Label } from "formsnap"; let labelEl: HTMLLabelElement; </script> <Label bind:el={labelEl}>Name</Label> ``` ```Svelte <script lang="ts"> import { Label } from "formsnap"; let labelRef = $state<HTMLLabelElement | null>(null); </script> <Label bind:ref={labelRef}>Name</Label> ``` -------------------------------- ### Svelte/TypeScript: Use Custom Label with Formsnap child snippet Source: https://www.formsnap.dev/docs/composition/child This example demonstrates how to use the `child` snippet within the Formsnap `Label` component to render a custom `<label>` HTML element. It shows how to import `Label`, use the `{#snippet child({ props })}` block, spread the `props` onto the custom element, and apply scoped CSS for custom styling. This allows for full control over the rendered HTML and styling. ```Svelte/TypeScript <script lang="ts"> import { Label } from "formsnap"; </script> <Label> {#snippet child({ props })} <label {...props} class="label">Name</label> {/snippet} </Label> <style> label { color: green; } </style> ``` -------------------------------- ### CSS: Style Formsnap Elements with Data Attributes Source: https://www.formsnap.dev/docs/styling This CSS snippet demonstrates how to target Formsnap components using their `data-fs-*` attributes. It shows examples of applying styles like `color: red` to elements with validation errors and `border: 1px solid #ccc` to form controls. This method allows for precise styling based on the component's state or role within the form. ```CSS [data-fs-error] { color: red; } [data-fs-control] { border: 1px solid #ccc; } /* ... */ ``` -------------------------------- ### Implement a Basic Signup Form with SvelteKit Superforms Only Source: https://www.formsnap.dev/docs/index This code snippet demonstrates how to create a simple signup form using only SvelteKit Superforms. It showcases the manual effort required for handling form data binding, client-side validation with Zod, and explicitly setting ARIA attributes for accessibility and displaying error messages. This approach can be verbose and prone to copy-paste errors. ```Svelte <script lang="ts"> import type { PageData } from "./$types"; import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { signupFormSchema } from "./schema"; let { data } = $props(); const { form, errors, enhance, constraints } = superForm(data.form, { validators: zodClient(signupFormSchema), }); </script> <form method="POST" use:enhance> <label for="name">Name</label> <input id="name" name="name" aria-describedby={$errors.name ? "name-error name-desc" : "name-desc"} aria-invalid={$errors.name ? "true" : undefined} aria-required={$constraints.name?.required ? "true" : undefined} bind:value={$form.name} /> <span id="name-desc">Be sure to use your real name.</span> <span id="name-error" aria-live="assertive"> {#if $errors.name.length} {#each $errors.name as err} {err} {#/each} {/if} </span> <label for="email">Email</label> <input id="email" name="email" type="email" aria-describedby={$errors.email ? "email-error email-desc" : "email-desc"} aria-invalid={$errors.email ? "true" : undefined} aria-required={$constraints.email?.required ? "true" : undefined} bind:value={$form.email} /> <span id="email-desc">It's preferred that you use your company email.</span> <span id="email-error" aria-live="assertive"> {#if $errors.email.length} {#each $errors.email as err} {err} {#/each} {if} </span> <label for="password">Password</label> <input id="password" name="password" type="password" aria-describedby={$errors.password ? "password-error password-desc" : "password-desc"} aria-invalid={$errors.password ? "true" : undefined} aria-required={$constraints.password?.required ? "true" : undefined} bind:value={$form.password} /> <span id="password-desc">Ensure the password is at least 10 characters.</span> <span id="password-error" aria-live="assertive"> {#if $errors.password.length} {#each $errors.password as err} {err} {#/each} {/if} </span> <button>Submit</button> </form> ``` -------------------------------- ### Implement Superforms and Formsnap for SvelteKit Forms Source: https://www.formsnap.dev/docs/index This snippet showcases a basic signup form utilizing SvelteKit Superforms for client-side validation with Zod and Formsnap for structured form field rendering. It demonstrates how to bind form data and display validation errors. Dependencies include 'sveltekit-superforms' and 'formsnap'. ```Svelte <script lang="ts"> import { Field, Control, Label, FieldErrors, Description } from "formsnap"; import { signupFormSchema } from "./schema.ts"; import { zodClient } from "sveltekit-superforms/adapters"; import { superForm } from "sveltekit-superforms"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(signupFormSchema), }); const { form: formData, enhance } = form; </script> <form method="POST" use:enhance> <Field {form} name="name"> <Control> {#snippet children({ props })} <Label>Name</Label> <input {...props} bind:value={$formData.name} /> {/snippet} </Control> <Description>Be sure to use your real name.</Description> <FieldErrors /> </Field> <Field {form} name="email"> <Control> {#snippet children({ props })} <Label>Email</Label> <input {...props} type="email" bind:value={$formData.email} /> {/snippet} </Control> <Description>It's preferred that you use your company email.</Description> <FieldErrors /> </Field> <Field {form} name="password"> <Control> {#snippet children({ props })} <Label>Password</Label> <input {...props} type="password" bind:value={$formData.password} /> {/snippet} </Control> <Description>Ensure the password is at least 10 characters.</Description> <FieldErrors /> </Field> </form> ``` -------------------------------- ### Initialize SvelteKit SuperForm for Multiple Select Source: https://www.formsnap.dev/docs/recipes/multiple-select This snippet initializes a SvelteKit SuperForm instance using `superForm` and `zodClient` for validation. It imports the schema, flavors, and toppings, and sets up the basic form structure with `use:form.enhance` for client-side enhancements. Dependencies: `sveltekit-superforms`, `sveltekit-superforms/adapters`, `zod`. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { schema, flavors, toppings } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema) }); const { form: formData } = form; </script> <form use:form.enhance method="POST"> <!-- ... --> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Formsnap Label Component API Reference Source: https://www.formsnap.dev/docs/components/label Detailed API documentation for the Formsnap `Label` component, outlining its available props and the data attributes automatically applied to the rendered element. This reference includes types and descriptions for each property. ```APIDOC Label Component Props: - ref: - type: HTMLElement | null - description: A $bindable reference to the underlying <label> element rendered by the Label component. - child: - type: Snippet - description: If provided, the Label component will not render an HTML element and will instead expect you to spread the snippet's props onto an element of your choosing. See the `child` snippet documentation for more information. - ...rest: - type: HTMLAttributes<HTMLLabelElement> - description: Any additional props provided to the Label component will be spread onto the underlying HTML element. Data Attributes: - data-fs-label: - type: '' - description: Applied to the element for selection during styling or otherwise. - data-fs-error: - type: '' | undefined - description: Applied to the element when a validation error exists on the field. ``` -------------------------------- ### Implement Single Select Form with SvelteKit and Bits UI Source: https://www.formsnap.dev/docs/recipes/bits-ui-select This Svelte component demonstrates how to integrate the `Select` component from Bits UI with Formsnap and `sveltekit-superforms` for single language selection. It binds the selected language to the form data, dynamically displays the chosen language label, and applies necessary accessibility and form submission props. The component relies on `sveltekit-superforms` for form handling, `bits-ui` for the select component, and Formsnap for field management. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { Select } from "bits-ui"; import { Field, Control, Label, FieldErrors, Description } from "formsnap"; import { schema, languages } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema) }); const { form: formData, enhance } = form; const selectedLanguageLabel = $derived( $formData.language ? languages[$formData.language] : "Select a language" ); </script> <form method="POST" use:enhance> <Field {form} name="language"> <Control> {#snippet children({ props })} <Label>Language</Label> <Select.Root type="single" bind:value={$formData.language} name={props.name}> <Select.Trigger {...props}> {selectedLanguageLabel} </Select.Trigger> <Select.Content> {#each Object.entries(languages) as [value, label]} <Select.Item {value}> {label} </Select.tItem> {/each} </Select.Content> </Select.Root> {/snippet} </Control> <Description>The docs will be translated to your preferred language.</Description> <FieldErrors /> </Field> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Svelte Formsnap Description Component Usage Source: https://www.formsnap.dev/docs/components/description Demonstrates how to use the `Description` component within a `Field` to provide additional context for an input field. It shows the `Description` linking to the `Control`. ```Svelte <Field name="name" {form}> <Control> {#snippet children({ props })} <Label>Name</Label> <input type="text" {...attrs} /> {/snippet} </Control> <Description>Your full name, including your middle name.</Description> </Field> ``` -------------------------------- ### Formsnap Description Component API Props Source: https://www.formsnap.dev/docs/components/description Details the properties accepted by the `Description` component, including standard HTML `<div>` props, `ref` for element access, and `child` for custom rendering. ```APIDOC Description Component Props: - ref: type: HTMLElement | null description: A reference to the underlying HTML element rendered by the `Description` component. example: <Description bind:ref={descriptionRef}> <!-- ... --> </Description> - child: type: Snippet description: If provided, the `Description` component will not render an HTML element and will instead expect you to spread the snippet's `props` onto an element of your choosing. See the `child` snippet documentation for more information. - ...rest: type: HTMLAttributes<HTMLElement> description: Any additional props provided to the `Description` component will be spread onto the underlying HTML element. ``` -------------------------------- ### Initialize SvelteKit SuperForm for Dynamic Fields Source: https://www.formsnap.dev/docs/recipes/dynamic-fields This snippet initializes a SvelteKit SuperForm instance, binding it to the form data from the load function and applying Zod client-side validation. It sets up the basic HTML form structure for submission. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { schema } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData } = form; </script> <form use:form.enhance method="POST"> <!-- ... --> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Import Formsnap Components for Form Building Source: https://www.formsnap.dev/docs/recipes/multiple-select This snippet demonstrates importing essential Formsnap components: `Field`, `Control`, `Label`, and `FieldErrors`. These components are crucial for structuring and displaying form elements and their associated validation messages within a SvelteKit SuperForm. Dependencies: `formsnap`. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { Field, Control, Label, FieldErrors } from "formsnap"; import { schema } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema) }); const { form: formData } = form; </script> <form use:form.enhance method="POST"> <!-- ... --> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Configure SvelteKit Load Function and Actions for Form Submission Source: https://www.formsnap.dev/docs/recipes/checkbox-groups This snippet sets up the `load` function and `actions` in a SvelteKit `+page.server.ts` file to handle form data. It uses `sveltekit-superforms` with the `zod` adapter to validate incoming form data against a shared schema, returning a 400 error with the form object if validation fails. This ensures server-side data integrity. ```typescript import { superValidate } from "sveltekit-superforms"; import type { Actions, PageServerLoad } from "./$types"; import { schema } from "./+page.svelte"; import { zod } from "sveltekit-superforms/adapters"; import { fail } from "@sveltejs/kit"; export const load: PageServerLoad = async () => { return { form: await superValidate(zod(schema)), }; }; export const actions: Actions = { default: async (event) => { const form = await superValidate(event, zod(schema)); if (!form.valid) { return fail(400, { form }); } return { form }; }, }; ``` -------------------------------- ### Import Formsnap Components for Dynamic Fields Source: https://www.formsnap.dev/docs/recipes/dynamic-fields This snippet extends the Svelte component by importing necessary Formsnap components like Fieldset, Legend, ElementField, Control, Label, FieldErrors, and Description. These components are essential for building the dynamic URL form structure. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { Fieldset, Legend, ElementField, Control, Label, FieldErrors, Description, } from "formsnap"; import { schema } from "./schema.js"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData } = form; </script> <form use:form.enhance method="POST"> <!-- ... --> <button type="submit">Submit</button> </form> ``` -------------------------------- ### Svelte: Import Formsnap Components and Enhance Form Source: https://www.formsnap.dev/docs/recipes/checkbox-groups This snippet demonstrates how to import necessary components from sveltekit-superforms and formsnap to initialize a SuperForm. It sets up a form element with the enhance action for client-side validation, binding the form data to a SuperForm instance. ```Svelte <script lang="ts"> import { superForm } from "sveltekit-superforms"; import { zodClient } from "sveltekit-superforms/adapters"; import { Fieldset, Legend, Label, Control, FieldErrors, Description } from "formsnap"; let { data } = $props(); const form = superForm(data.form, { validators: zodClient(schema), }); const { form: formData } = form; </script> <form method="POST" use:form.enhance> <!-- ... --> <button type="submit">Submit</button> </form> ``` -------------------------------- ### useFormField Hook API Reference Source: https://www.formsnap.dev/docs/composition/use-form-field This section provides a detailed API reference for the `useFormField` hook, outlining its configurable properties and the structure of the object it returns. It covers the `errorsId` and `descriptionId` props, and the `UseFormFieldReturn` type with its various state properties. ```APIDOC Props: errorsId: type: () => string | undefined | null description: Optionally provide a getter function that returns a custom ID to override the errors container ID. descriptionId: type: () => string | undefined | null description: Optionally provide a getter function that returns a custom ID to override the description container ID. Return Type: UseFormFieldReturn<T extends Record<string, unknown>, U extends FormPath<T>>: form: SuperForm<T> (The original form store passed to the `*Field` component.) readonly errorsId: string (Reactive state containing the ID of the field errors container for the field.) readonly descriptionId: string (Reactive state containing the ID of the description element for the field.) readonly name: U (Reactive state containing the name of the field.) readonly errors: string[] (Reactive state containing the current validations errors for the field.) readonly constraints: Record<string, unknown> (Reactive state containing the constraints (if any) for the field.) readonly tainted: boolean (Reactive state containing the tainted state of the field.) Warning: The `useFormField` function returns getters for the various reactive states. You should not destructure the object returned by `useFormField` and instead use the getters directly. ``` -------------------------------- ### Migrate Formsnap `*Field*` components from slot props to snippet props in Svelte Source: https://www.formsnap.dev/docs/v2-migration-guide Formsnap v2 now provides access to `*Field*` component inner state (e.g., `value`, `errors`, `tainted`, `constraints`) via snippet props within the `children` snippet, replacing the previous slot prop mechanism. This requires wrapping your field content in a `{#snippet children({ ...props })}` block to access these values. If no state access is needed, the `children` snippet can be omitted. ```Svelte <Field {form} name="name" let:value let:errors let:tainted let:constraints> <!-- ... you can access those slot props here --> </Field> ``` ```Svelte <Field {form} name="name"> {#snippet children({ value, errors, tainted, constraints })} <!-- ... you can access those snippet props here --> {/snippet} </Field> <!-- or if you don't need access to those values --> <Field {form} name="name"> <!-- ... your form components here --> </Field> ``` -------------------------------- ### Svelte: Implement useFormControl in a Custom Input Component Source: https://www.formsnap.dev/docs/composition/use-form-control This Svelte snippet demonstrates creating a `LabelInput.svelte` component that leverages `useFormControl` to access and apply control and label attributes to custom `CustomLabel` and `CustomInput` components. It illustrates how to build reusable form elements with advanced composition. ```Svelte <script lang="ts"> import { useFormControl } from "formsnap"; import CustomLabel from "$lib/components/CustomLabel.svelte"; import CustomInput from "$lib/components/CustomInput.svelte"; let { label }: { label: string } = $props(); const control = useFormControl(); </script> <CustomLabel {...control.labelProps}> {label} </CustomLabel> <CustomInput {...control.props} /> ``` -------------------------------- ### APIDOC: Fieldset Component Props Source: https://www.formsnap.dev/docs/components/fieldset Defines the properties accepted by the `Fieldset` component, including required form and name props, and optional ref, child, and rest attributes. ```APIDOC Fieldset Component Props: - form: type: SuperForm<T> description: The form object returned from calling `superForm` in your component. required: true - name: type: FormPath<T> description: The path to the field in the form object. required: true - ref: type: HTMLElement | null description: A $bindable reference to the underlying HTML element rendered by the `Fieldset` component. - child: type: Snippet description: If provided, the `Fieldset` component will not render an HTML element and will instead expect you to spread the snippet's `props` onto an element of your choosing. See the `child` snippet documentation for more information. - ...rest: type: HTMLAttributes<HTMLFieldSetElement> description: Any additional props provided to the `Fieldset` component will be spread onto the underlying HTML element. ``` -------------------------------- ### Formsnap Description Component Data Attributes Source: https://www.formsnap.dev/docs/components/description Lists the data attributes automatically applied to the `Description` component's underlying `<div>` element, useful for styling or selection. ```APIDOC Description Component Data Attributes: - data-fs-description: type: '' description: Applied to the description element for selection during styling or otherwise. - data-fs-error: type: '' | undefined description: Applied to the description element when a validation error exists on the field. ``` -------------------------------- ### API Reference: Field Component Props Source: https://www.formsnap.dev/docs/components/field Documents the required props for the Formsnap `Field` component, including the form object from Superforms and the field's path. ```APIDOC Class/Component: Field Props: form: Type: SuperForm<T> Description: The form object returned from calling `superForm` in your component. Required: true name: Type: FormPath<T> Description: The path to the field in the form object. Required: true ``` -------------------------------- ### ElementField Component Props API Reference Source: https://www.formsnap.dev/docs/components/element-field Defines the properties available for configuring the ElementField component. These props are essential for linking the component to a SuperForm instance and specifying the target field path within the form data structure. ```APIDOC ElementField Props: - form: Type: SuperForm<T> Description: The form object returned from calling `superForm` in your component. Required: true - name: Type: FormPathLeaves<T> Description: The path to the field in the form object. Required: true ``` -------------------------------- ### Legend Component Props Reference Source: https://www.formsnap.dev/docs/components/legend Documents the properties accepted by the Formsnap Legend component. This includes standard HTML <legend> element attributes, along with Formsnap-specific props like 'ref' for element binding and 'child' for advanced composition patterns. ```APIDOC Legend Component Props: - "ref": "type": "HTMLElement | null" "description": "A $bindable reference to the underlying HTML element rendered by the Legend component." - "child": "type": "Snippet" "description": "If provided, the Legend component will not render an HTML element and will instead expect you to spread the snippet's props onto an element of your choosing. See the `child` snippet documentation for more information." - "...rest": "type": "HTMLAttributes<HTMLLegendElement>" "description": "Any additional props provided to the Legend component will be spread onto the underlying HTML element." ```