Making SvelteKit forms a pleasure to use with comprehensive validation, type safety, and progressive enhancement.
npx @tessl/cli install tessl/npm-sveltekit-superforms@2.27.00
# SvelteKit Superforms
1
2
SvelteKit Superforms is a comprehensive form handling library that makes form validation, data binding, and error management a pleasure to use in SvelteKit applications. It provides type-safe form handling with progressive enhancement, supporting 12+ validation libraries and offering seamless client-server integration.
3
4
## Package Information
5
6
- **Package Name**: sveltekit-superforms
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install sveltekit-superforms`
10
11
## Core Imports
12
13
```typescript
14
import { superForm, superValidate } from "sveltekit-superforms";
15
import { zod } from "sveltekit-superforms/adapters";
16
import { z } from "zod";
17
```
18
19
For client-only imports:
20
21
```typescript
22
import { superForm } from "sveltekit-superforms/client";
23
```
24
25
For server-only imports:
26
27
```typescript
28
import { superValidate, message, setError } from "sveltekit-superforms/server";
29
```
30
31
## Basic Usage
32
33
```typescript
34
// schema.ts
35
import { z } from "zod";
36
export const schema = z.object({
37
name: z.string().min(2),
38
email: z.string().email(),
39
age: z.number().min(18)
40
});
41
42
// +page.server.ts
43
import { superValidate } from "sveltekit-superforms/server";
44
import { zod } from "sveltekit-superforms/adapters";
45
import { schema } from "./schema.js";
46
47
export const load = async () => {
48
const form = await superValidate(zod(schema));
49
return { form };
50
};
51
52
export const actions = {
53
default: async ({ request }) => {
54
const form = await superValidate(request, zod(schema));
55
56
if (!form.valid) {
57
return fail(400, { form });
58
}
59
60
// Process valid form data
61
console.log(form.data);
62
return { form };
63
}
64
};
65
66
// +page.svelte
67
<script lang="ts">
68
import { superForm } from "sveltekit-superforms/client";
69
70
export let data;
71
72
const { form, errors, enhance } = superForm(data.form);
73
</script>
74
75
<form method="POST" use:enhance>
76
<input name="name" bind:value={$form.name} />
77
{#if $errors.name}<span class="error">{$errors.name}</span>{/if}
78
79
<input name="email" type="email" bind:value={$form.email} />
80
{#if $errors.email}<span class="error">{$errors.email}</span>{/if}
81
82
<input name="age" type="number" bind:value={$form.age} />
83
{#if $errors.age}<span class="error">{$errors.age}</span>{/if}
84
85
<button type="submit">Submit</button>
86
</form>
87
```
88
89
## Architecture
90
91
SvelteKit Superforms is built around several key architectural components:
92
93
- **Validation Adapters**: Unified interface for 12+ validation libraries (Zod, Yup, Joi, etc.)
94
- **Server Integration**: `superValidate` function for server-side form processing and validation
95
- **Client Management**: `superForm` function creating reactive Svelte stores for form state
96
- **Type Safety**: Complete TypeScript integration with schema inference and type preservation
97
- **Progressive Enhancement**: Forms work without JavaScript, enhanced when available
98
- **Proxy System**: Type-safe field binding with automatic string conversion for HTML inputs
99
- **Error Handling**: Comprehensive error management with field-level and form-level errors
100
101
## Capabilities
102
103
### Server-Side Validation
104
105
Complete server-side form processing with validation, error handling, and data coercion. Handles form submissions, file uploads, and integrates with SvelteKit's action system.
106
107
```typescript { .api }
108
function superValidate<Out, Message, In>(
109
adapter: ValidationAdapter<Out, In>,
110
options?: SuperValidateOptions<Out>
111
): Promise<SuperValidated<Out, Message, In>>;
112
113
function superValidate<Out, Message, In>(
114
data: RequestEvent | Request | FormData | URLSearchParams | URL | Partial<In> | null | undefined,
115
adapter: ValidationAdapter<Out, In>,
116
options?: SuperValidateOptions<Out>
117
): Promise<SuperValidated<Out, Message, In>>;
118
```
119
120
[Server-Side Processing](./server-processing.md)
121
122
### Client-Side Form Management
123
124
Reactive form management with Svelte stores, real-time validation, error handling, and progressive enhancement features.
125
126
```typescript { .api }
127
function superForm<T, M>(
128
form: SuperValidated<T, M>,
129
options?: FormOptions<T, M>
130
): SuperForm<T, M>;
131
132
interface SuperForm<T, M> {
133
form: SuperFormData<T>;
134
formId: Writable<string>;
135
errors: SuperFormErrors<T>;
136
constraints: Writable<InputConstraints<T>>;
137
message: Writable<M | undefined>;
138
tainted: Writable<TaintedFields<T> | undefined>;
139
submitting: Readable<boolean>;
140
delayed: Readable<boolean>;
141
timeout: Readable<boolean>;
142
posted: Readable<boolean>;
143
allErrors: Readable<{ path: string; messages: string[] }[]>;
144
enhance: (el: HTMLFormElement, events?: SuperFormEvents<T, M>) => ReturnType<SubmitFunction>;
145
isTainted: (path?: FormPath<T> | Record<string, unknown> | boolean | undefined) => boolean;
146
reset: (options?: ResetOptions<T>) => void;
147
submit: (submitter?: HTMLElement | Event | EventTarget | null) => void;
148
validate: <Path extends FormPathLeaves<T>>(path: Path, opts?: ValidateOptions<FormPathType<T, Path>, Partial<T>, Record<string, unknown>>) => Promise<string[] | undefined>;
149
validateForm: <P extends Partial<T> = T>(opts?: { update?: boolean; schema?: ValidationAdapter<P>; focusOnError?: boolean; }) => Promise<SuperFormValidated<T, M>>;
150
capture: () => SuperFormSnapshot<T, M>;
151
restore: (snapshot: SuperFormSnapshot<T, M>) => void;
152
// ... other methods and properties documented in detail in sub-docs
153
}
154
```
155
156
[Client-Side Management](./client-management.md)
157
158
### Field Proxies and Data Binding
159
160
Type-safe proxy functions for binding form fields with automatic string conversion, supporting various data types including numbers, dates, booleans, arrays, and files.
161
162
```typescript { .api }
163
function fieldProxy<T, Path>(
164
form: Writable<T> | SuperForm<T>,
165
path: Path,
166
options?: ProxyOptions
167
): FieldProxy<FormPathType<T, Path>>;
168
169
function intProxy<T, Path>(
170
form: Writable<T> | SuperForm<T>,
171
path: Path,
172
options?: ProxyOptions
173
): Writable<string>;
174
175
function dateProxy<T, Path>(
176
form: Writable<T> | SuperForm<T>,
177
path: Path,
178
options?: { dateFormat?: 'date' | 'datetime' | 'time' | 'iso'; taint?: TaintOption }
179
): Writable<string>;
180
```
181
182
[Field Proxies](./field-proxies.md)
183
184
### Validation Adapters
185
186
Unified adapters for 12+ popular validation libraries, providing consistent interface and type inference across different schema validation approaches.
187
188
```typescript { .api }
189
function zod<T>(
190
schema: ZodObjectType<T>,
191
options?: AdapterOptions<T>
192
): ValidationAdapter<T>;
193
194
function yup<T>(
195
schema: YupSchema<T>,
196
options?: AdapterOptions<T>
197
): ValidationAdapter<T>;
198
199
function joi<T>(
200
schema: JoiSchema<T>,
201
options?: AdapterOptions<T>
202
): ValidationAdapter<T>;
203
204
// ... and 9 more adapters
205
```
206
207
[Validation Adapters](./validation-adapters.md)
208
209
## Core Types
210
211
```typescript { .api }
212
interface SuperValidated<Out, Message = any, In = Out> {
213
id: string;
214
valid: boolean;
215
posted: boolean;
216
errors: ValidationErrors<Out>;
217
data: Out;
218
constraints?: InputConstraints<Out>;
219
message?: Message;
220
shape?: SchemaShape;
221
}
222
223
interface ValidationErrors<T> {
224
_errors?: string[];
225
[K in keyof T]?: T[K] extends Record<string, unknown>
226
? ValidationErrors<T[K]>
227
: T[K] extends Array<infer U>
228
? U extends Record<string, unknown>
229
? Array<ValidationErrors<U> | undefined>
230
: string[]
231
: string[];
232
}
233
234
interface FormOptions<T, M, In = T> {
235
id?: string;
236
applyAction?: boolean | 'never';
237
invalidateAll?: boolean | 'force' | 'pessimistic';
238
resetForm?: boolean | (() => boolean);
239
scrollToError?: 'auto' | 'smooth' | 'off' | boolean | ScrollIntoViewOptions;
240
autoFocusOnError?: boolean | 'detect';
241
errorSelector?: string;
242
selectErrorText?: boolean;
243
stickyNavbar?: string;
244
taintedMessage?: string | boolean | null | ((nav: BeforeNavigate) => Promise<boolean>);
245
spa?: boolean | { failover?: boolean };
246
dataType?: 'form' | 'json';
247
validators?: ValidationAdapter<Partial<T>> | ClientValidationAdapter<Partial<T>> | false | 'clear';
248
customValidity?: boolean;
249
clearOnSubmit?: 'errors' | 'message' | 'errors-and-message' | 'none';
250
multipleSubmits?: 'prevent' | 'allow' | 'abort';
251
SPA?: { failover?: boolean };
252
flashMessage?: {
253
module: { getFlash(page: Page): FlashMessage };
254
onError?: ({ result, message }: { result: ActionResult; message: FlashMessage }) => void;
255
};
256
onError?: (event: { result: ActionResult; message?: any }) => void;
257
onResult?: (event: { result: ActionResult; formEl: HTMLFormElement; cancel: () => void }) => void;
258
onSubmit?: (event: { formData: FormData; formElement: HTMLFormElement; controller: AbortController; cancel: () => void }) => void;
259
onUpdate?: (event: { form: SuperValidated<T, M>; formEl: HTMLFormElement; cancel: () => void }) => void;
260
onUpdated?: (event: { form: SuperValidated<T, M>; formEl: HTMLFormElement }) => void;
261
}
262
263
type ValidationAdapter<Out, In = Out> = {
264
superFormValidationLibrary: ValidationLibrary;
265
validate: (data: unknown) => Promise<ValidationResult<Out>>;
266
jsonSchema: JSONSchema;
267
defaults: Out;
268
constraints: InputConstraints<Out>;
269
shape: SchemaShape;
270
id: string;
271
};
272
273
type FormPath<T, Type = any> = string; // Path to any property in T
274
type FormPathLeaves<T, Type = any> = string; // Path to leaf properties only
275
type FormPathType<T, Path extends string> = any; // Type at path in T
276
277
type TaintedFields<T> = {
278
[K in keyof T]?: T[K] extends Record<string, unknown>
279
? TaintedFields<T[K]>
280
: T[K] extends Array<any>
281
? boolean[]
282
: boolean;
283
};
284
285
type Infer<T> = T; // Infer output type from schema
286
type InferIn<T> = T; // Infer input type from schema
287
```