SvelteKit Superforms

repository·main·Indexed 25 days ago

https://github.com/ciscoheat/sveltekit-superforms

A powerful library for SvelteKit that simplifies form handling, validation, and data synchronization between server and client. It supports multiple validation adapters including Zod, Valibot, Yup, Joi, TypeBox, and others, and provides features like progressive enhancement, nested data structure support, and UX enhancements such as auto-focusing invalid fields and tainted form detection.

Tokens
5.6K
Snippets
2
Records
43
Agent score
83%

What's inside sveltekit-superforms

  1. Overview of Superforms features

    main

    Superforms is a library designed to make SvelteKit forms easier to use. Key features include:

    • Validation: Supports server- and client-side validation using libraries like Zod, Valibot, Yup, Joi, TypeBox, Superstruct, Arktype, Effect, class-validator, and VineJS, or via JSON Schema.
    • Data Handling: Automatically coerces FormData into correct types (including arrays and files), supports nested data structures, and generates default form values from schemas.
    • UX Enhancements: Features auto-centering/focusing on invalid fields, tainted form detection (to prevent data loss), and real-time client-side validation.
    • SvelteKit Integration: Seamlessly merges PageData and ActionData with strong typing, supports multiple forms per page, and works in both standard SvelteKit and SPA modes.
    • Progressive Enhancement: Works without JavaScript by default but provides full support for progressive enhancement.
    • Advanced Tools: Includes proxy objects for data conversion, auto-updating timers for loading states, and a SuperDebug Svelte component for debugging.
  2. Configure FormOptions for superForm

    main

    The FormOptions object allows you to customize the behavior of your form. Key options include:

    • id: A unique string to identify the form (useful for multiple forms on one page).
    • applyAction: Whether the form reacts to page state updates. Default is true. Set to 'never' to disable all reactions.
    • invalidateAll: Controls how page invalidations affect the form. Options: true, 'force', or 'pessimistic'.
    • resetForm: A boolean or function determining if the form resets after a successful submission. Default is true.
    • scrollToError: Controls how the browser scrolls to the first error. Options: 'auto', 'smooth', 'off', or boolean or ScrollIntoViewOptions.
    • autoFocusOnError: Whether to focus the first error field. Options: true or 'detect'.
    • dataType: Set to 'json' if your form contains nested data structures (objects/arrays). Default is 'form'.
    • validators: A client-side validation adapter.
    • validationMethod: When to trigger validation. Options: 'auto', 'oninput', 'onblur', 'onsubmit', or 'submit-only'.
    • SPA: Enable Single Page Application mode by setting to true. Note that string and { failStatus } options are deprecated.
    • onSubmit: A callback triggered before submission. Can be used to provide jsonData, override validators, or provide a customRequest.
    • onResult, onUpdate, onUpdated, onError: Lifecycle callbacks for handling form submission results and errors.
  3. Configure superValidate options

    main

    When calling superValidate, you can provide a SuperValidateOptions object to customize the validation process.

    OptionTypeDescription
    errorsbooleanWhether to include errors in the result. Defaults to true unless strict is set.
    idstringA unique identifier for the form instance.
    preprocessed(keyof Out)[]An array of keys to be preprocessed before validation.
    defaultsOutExplicit default values to use.
    jsonSchemaJSONSchemaThe JSON schema associated with the validator.
    strictbooleanIf true, validation is stricter and does not merge with defaults.
    allowFilesbooleanWhether to allow File objects in the data.
    transportTransportThe transport mechanism used for the form.
  4. Handle form submission with enhance()

    main

    To enable Superforms' enhanced client-side handling, use the enhance method returned by superForm on your HTML form element. This allows for features like client-side validation, automatic error handling, and SPA mode.

    <script>
      const { form, errors, enhance } = superForm(data.form);
    </script>
    
    <form method="POST" use:enhance>
      <input name="email" bind:value={$form.email} />
      {#if $errors.email}<span>{$errors.email}</span>{/if}
      <button>Submit</button>
    </form>
  5. Enhance a form with `enhance`

    main

    The enhance method (returned by superForm) is used to attach SvelteKit's use:enhance functionality with Superforms' client-side features (like validation, taint tracking, and error handling) to an HTML form.

    Parameters:

    • FormElement: The HTML form element to enhance.
    • events?: An optional object to register custom event handlers:
      • onSubmit: Called before the form is submitted.
      • onResult: Called when the server responds.
      • onUpdate: Called when the form data is updated.
      • onUpdated: Called after the form is updated.
      • onError: Called when an error occurs.
  6. Add messages to forms with message()

    main

    The message function (and its alias setMessage) allows you to attach a message to a SuperValidated object. This is useful for returning success or error notifications to the client.

    If an options.status is provided and is $\ge 400$, form.valid will be automatically set to false.

    Options:

    • status: An ErrorStatus (HTTP status code). If $\ge 400$, the form is marked invalid.
    • removeFiles: Boolean. If true (default), File objects are stripped from the returned object to prevent issues with serialization.
  7. Initialize a form with superForm()

    main
    The superForm function initializes a SvelteKit form for convenient handling of values, errors, and submission. It takes the validated form data (usually from data.form in SvelteKit) and an optional configuration object. It returns a SuperForm object containing stores for the form data, errors, constraints, and more.
  8. Validate data with superValidate

    main

    The superValidate function is the primary entry point for server-side validation in Superforms. It takes a validation adapter (like Zod, Valibot, etc.) and optional data to produce a SuperValidated object containing the validated data, errors, and constraints.

    It can accept several types of input data:

    • RequestEvent (from SvelteKit actions)
    • Request
    • FormData
    • URLSearchParams
    • URL
    • Partial<In> (a partial object of the expected input type)
    • null or undefined (uses schema defaults)

    Usage Patterns:

    1. Validate with defaults (initial load):

      const form = await superValidate(adapter);
    2. Validate submitted form data:

      const form = await superValidate(request, adapter);
    3. Validate with specific options:

      const form = await superValidate(request, adapter, { strict: true });
  9. Generate JSON Schema using simpleSchema()

    main

    The simpleSchema function acts as a generator to create a JSONSchema from a sample value. This is useful for validation libraries that lack introspection capabilities. It recursively traverses the provided value to infer types, properties, and required fields.

    Inference Rules:

    • Primitives: Uses typeof to determine the type (e.g., 'string', 'number', 'boolean').
    • Dates: Converts Date instances to { type: 'integer', format: 'unix-time' }.
    • Arrays: Returns { type: 'array' }. The items property is inferred from the first element of the array (value[0]). If the array is empty, items is an empty object {}.
    • Objects: Returns { type: 'object' } with additionalProperties: false.
      • properties: Recursively generated for every key in the object.
      • required: A key is marked as required if its value is falsy (but not null or undefined) or if it is an empty array.
    • Null/Undefined: Returns an empty object {}.