Skip to content
Andreas Söderlund edited this page Feb 28, 2023 · 32 revisions

Types

Throughout the reference, the following types are represented:

// T represents the validation schema
T extends AnyZodObject

// S refers to the underlying type of the schema, the actual data structure.
S = z.infer<T>
export type ValidationErrors<T> = Partial<
  Record<keyof S, string[] | undefined>
>;
export type InputConstraints = Partial<{
  pattern: string;
  min: number | string;
  max: number | string;
  required: boolean;
  step: number;
  minlength: number;
  maxlength: number;
}>
export type Validation<T> = {
  valid: boolean;
  errors: ValidationErrors<T>;
  data: S;
  empty: boolean;
  message: string | null;
  constraints: Record<keyof S, InputConstraints>
};

Server

import {
  superValidate,
  setError,
  noErrors,
  actionResult
} from 'sveltekit-superforms/server';

superValidate(data, schema, options?)

superValidate(
  data:
    | RequestEvent
    | Request
    | FormData
    | Partial<S>
    | null
    | undefined,
  schema: T,
  options?: {
    implicitDefaults = true; // See further down for default entity values
    noErrors = false; // See noErrors() reference
  }
): Promise<Validation<T>>

If data is determined to be empty (null, undefined or no FormData), a validation result with a default entity for the schema is returned, in this shape:

{
  valid: false;
  errors: {};
  data: S; // See further down for default entity values.
  empty: true;
  message: null;
}

setError(form, field, error)

setError(
  form: Validation<T>,
  field: keyof S,
  error: string | string[] | null
) : ActionFailure<{form: Validation<T>}>

If you want to set an error on the form outside validation, use setError. It returns a fail(400, { form }) so it can be returned immediately, or more errors can be added by calling it multiple times before returning.

noErrors(form)

If you want to return a form with no validation errors. Only the errors property will be modified, so valid still indicates the validation status. Useful for load functions where the entity is invalid, but as an initial state no errors should be displayed on the form.

noErrors(form: Validation<T>) : Validation<T>

actionResult(type, data?, status?)

When not using form actions, this constructs an action result in a Response object, so you can return Validation<T> from your API/endpoints, for example in a login request:

src/routes/login/+server.ts

import { actionResult, superValidate } from '$lib/server';
import { z } from 'zod';
import type { RequestHandler } from './$types';

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(5)
});

export const POST = (async (event) => {
  const form = await superValidate(event, loginSchema);
  if (!form.valid) return actionResult('failure', { form });

  // Verify login here //

  return actionResult('success', { form });
}) satisfies RequestHandler;

Client

import {
  superForm,
  intProxy,
  numberProxy,
  booleanProxy,
  dateProxy
} from 'sveltekit-superforms/client';

superForm(form?, options?)

superForm(
  form?: FormOptions<T> | Validation<T> | null | undefined,
  options?: FormOptions<T>
) : EnhancedForm<T>
type FormOptions<T extends AnyZodObject> = {
  applyAction?: boolean;
  autoFocusOnError?: boolean | 'detect';
  clearOnSubmit?: 'errors' | 'message' | 'errors-and-message' | 'none';
  dataType?: 'form' | 'formdata' | 'json';
  defaultValidator?: 'clear' | 'keep';
  delayMs?: number;
  errorSelector?: string;
  invalidateAll?: boolean;
  multipleSubmits?: 'prevent' | 'allow' | 'abort';
  resetForm?: boolean;
  scrollToError?: 'auto' | 'smooth' | 'off';
  stickyNavbar?: string;
  taintedMessage?: string | null | false;
  timeoutMs?: number;
  validators?: Validators<T>;

  onSubmit?: (...params: Parameters<SubmitFunction>) => unknown | void;

  async onResult?: (event: {
    result: ActionResult;
    update: async (
      result: ActionResult<'success' | 'failure'>,
      untaint?: boolean
    );
    formEl: HTMLFormElement;
    cancel: () => void;
  })

  async onUpdate?: (event: {
    form: Validation<T>;
    cancel: () => void;
  })

  async onUpdated?: (event: {
    form: Validation<T>;
  })

  async onError?:
    | async (
        result: ActionResult<'error'>,
        message: Writable<string | null>
      )
    | 'set-message'
    | 'apply'
    | string;

  flashMessage?: {
    module: (import * as module from 'sveltekit-flash-message/client'),
    onError?: (errorResult: ActionResult<'error'>) => App.PageData['flash']
  };
};
type EnhancedForm<T extends AnyZodObject> = {
  form: Writable<Validation<T>['data']>;
  errors: Writable<Validation<T>['errors']>;
  message: Writable<string | null>;

  success: Readable<boolean>;
  empty: Readable<boolean>;

  submitting: Readable<boolean>;
  delayed: Readable<boolean>;
  timeout: Readable<boolean>;

  firstError: Readable<{ key: string; value: string } | null>;
  allErrors: Readable<{ key: string; value: string }[]>;

  enhance: (el: HTMLFormElement) => ReturnType<typeof formEnhance>;
  reset: () => void;

  async update: (
    result: ActionResult<'success' | 'failure'>,
    untaint?: boolean
  )
};

intProxy(form, fieldName) : Writable

Creates a proxy store for an integer form field. Changes in either the proxy store or the form field will reflect in the other.

numberProxy(form, fieldName) : Writable

Creates a proxy store for a numeric form field. Changes in either the proxy store or the form field will reflect in the other.

booleanProxy(form, fieldName, { trueStringValue = 'true' }) : Writable

Creates a proxy store for a boolean form field. Changes in either the proxy store or the form field will reflect in the other. The option can be used to change what string value represents true.

dateProxy(form, fieldName, { format: 'date-local' | 'datetime-local' | 'time-local' | 'iso' = 'iso' ) : Writable

Creates a proxy store for a boolean form field. Changes in either the proxy store or the form field will reflect in the other. The option can be used to format the string value differently, based on the input type for example.

Components

import SuperDebug from 'sveltekit-superforms/client/SuperDebug.svelte';
<SuperDebug
  data={any}
  display?={true}
  status?={true}
  stringTruncate?={120}
  ref?={HTMLPreElement}
/>
Clone this wiki locally