-
Notifications
You must be signed in to change notification settings - Fork 27
/
+page.md
806 lines (575 loc) · 24.2 KB
/
+page.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
<script lang="ts">
import Head from '$lib/Head.svelte';
import Form from './Form.svelte';
import SuperDebug from 'sveltekit-superforms/client/SuperDebug.svelte';
import Installer from './Installer.svelte';
import SvelteLab from './SvelteLab.svelte';
import { getSettings } from '$lib/settings';
export let data;
const settings = getSettings();
if(data.lib) {
$settings.lib = data.lib;
}
let formComponent
$: form = formComponent && formComponent.formData()
</script>
<Head title="Get started - Tutorial for Superforms" />
# Get started
<Installer />
Select your environment above and run the install command in your project folder.
{#if $settings.lib == 'json-schema'}
If you're using JSON Schema on the client, you also need to modify **vite.config.ts**:
```ts
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
}
});
```
{/if}
If you're starting from scratch, create a new SvelteKit project:
{#if $settings.pm == 'npm i -D'}
```npm
npm create svelte@latest
```
{:else if $settings.pm == 'pnpm i -D'}
```npm
pnpm create svelte@latest
```
{:else if $settings.pm == 'yarn add --dev'}
```npm
yarn create svelte@latest
```
{/if}
<SvelteLab lib={$settings.lib} />
{#if ['', 'ajv', 'n/a'].includes($settings.lib)}
> Please select a validation library above before continuing, as the tutorial changes depending on that.
{/if}
## Creating a Superform
This tutorial will create a Superform containing a name and an email address, ready to be expanded with more form data.
### Creating a validation schema
The main thing required to create a Superform is a validation schema, representing the form data for a single form.
{#if $settings.lib == 'arktype'}
```ts
import { type } from 'arktype';
const schema = type({
name: 'string',
email: 'email'
});
```
{:else if $settings.lib == 'class-validator'}
```ts
import { IsEmail, IsString, MinLength } from 'class-validator';
class ClassValidatorSchema {
@IsString()
@MinLength(2)
name: string = '';
@IsString()
@IsEmail()
email: string = '';
}
export const schema = ClassValidatorSchema;
```
{:else if $settings.lib == 'effect'}
```ts
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' }
})
)
});
```
{:else if $settings.lib == 'joi'}
```ts
import Joi from 'joi';
const schema = Joi.object({
name: Joi.string().default('Hello world!'),
email: Joi.string().email().required()
});
```
{:else if $settings.lib == 'json-schema'}
```ts
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
```
> Currently, definitions and references ($ref properties in the JSON Schema) aren't supported. You need to resolve the references yourself before using the adapter.
{:else if $settings.lib == 'superstruct'}
```ts
import { object, string, defaulted, define } from 'superstruct';
const email = () => define<string>('email', (value) => String(value).includes('@'));
export const schema = object({
name: defaulted(string(), 'Hello world!'),
email: email()
});
```
{:else if $settings.lib == '@sinclair/typebox'}
```ts
import { Type } from '@sinclair/typebox';
const schema = Type.Object({
name: Type.String({ default: 'Hello world!' }),
email: Type.String({ format: 'email' })
});
```
{:else if $settings.lib == 'valibot'}
```ts
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())
});
```
{:else if $settings.lib == '@vinejs/vine'}
```ts
import Vine from '@vinejs/vine';
const schema = Vine.object({
name: Vine.string(),
email: Vine.string().email()
});
```
{:else if $settings.lib == 'yup'}
```ts
import { object, string } from 'yup';
const schema = object({
name: string().default('Hello world!'),
email: string().email().required()
});
```
{:else if $settings.lib == 'zod'}
```ts
import { z } from 'zod';
const schema = z.object({
name: z.string().default('Hello world!'),
email: z.string().email()
});
```
{:else}
> Select a validation library at the top of the page to see the example code.
{/if}
#### Schema caching
The schema should be defined outside the load function, in this case on the top level of the module. **This is very important to make caching work.** The adapter is memoized (cached) with its arguments, so they must be kept in memory. Therefore, define the schema, its options and potential defaults on the top level of a module, so they always refer to the same object.
### Initializing the form in the load function
To initialize the form, you import an adapter corresponding to your library of choice, together with the schema, and pass it in a load function to the `superValidate` function:
**src/routes/+page.server.ts**
{#if $settings.lib == 'arktype'}
```ts
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',
email: 'email'
});
// Defaults should also be defined outside the load function
const defaults = { name: 'Hello world!', email: '' };
export const load = async () => {
// Arktype requires explicit default values for now
const form = await superValidate(arktype(schema, { defaults }));
// Always return { form } in load functions
return { form };
};
```
{:else if $settings.lib == 'class-validator'}
```ts
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 };
};
```
{:else if $settings.lib == 'effect'}
```ts
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 };
};
```
{:else if $settings.lib == 'joi'}
```ts
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 };
};
```
{:else if $settings.lib == 'json-schema'}
```ts
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 };
};
```
{:else if $settings.lib == 'superstruct'}
```ts
import { superValidate } from 'sveltekit-superforms';
import { superstruct } from 'sveltekit-superforms/adapters';
import { object, string, defaulted, define } from 'superstruct';
const email = () => define<string>('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 };
};
```
{:else if $settings.lib == '@sinclair/typebox'}
```ts
import { superValidate } from 'sveltekit-superforms';
import { typebox } from 'sveltekit-superforms/adapters';
import { Type } from '@sinclair/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 };
};
```
{:else if $settings.lib == 'valibot'}
```ts
import { superValidate } from 'sveltekit-superforms';
import { valibot } from 'sveltekit-superforms/adapters';
import { object, string, email, optional, pipe, 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 };
};
```
{:else if $settings.lib == '@vinejs/vine'}
```ts
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 };
};
```
{:else if $settings.lib == 'yup'}
```ts
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 };
};
```
{:else if $settings.lib == 'zod'}
```ts
import { superValidate } from 'sveltekit-superforms';
import { zod } 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.string().email()
});
export const load = async () => {
const form = await superValidate(zod(schema));
// Always return { form } in load functions
return { form };
};
```
{:else}
> Select a validation library at the top of the page to see the example code.
{/if}
The Superform server API is called `superValidate`. You can call it in two ways in the load function:
### Empty form
If you want the form to be initially empty, just pass the adapter as in the example above, and the form will be filled with default values based on the schema. For example, a `string` field results in an empty string, unless you have set a default.
### Populate form from database
If you want to populate the form, you can send data to `superValidate` as the first parameter, adapter second, like this:
```ts
import { error } from '@sveltejs/kit';
export const load = async ({ params }) => {
// Replace with your database
const user = 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 };
};
```
As long as the data partially matches the schema, you can pass it directly to `superValidate`. This is useful for backend interfaces, where the form should usually be populated based on a url like `/users/123`.
> Errors will be automatically displayed when the form is populated like this, but not when empty. You can modify this behavior [with an option](/concepts/error-handling#initial-form-errors).
### Important note about return values
Unless you call the SvelteKit `redirect` or `error` functions, you should **always** return the form object to the client, either directly or through a helper function. The name of the variable doesn't matter; you can call it `{ loginForm }` or anything else, but it needs to be returned like this in all code paths that returns, both in load functions and form actions.
### Displaying the form
The `superValidate` function returns the data required to instantiate a form on the client, now available in `+page.svelte` as `data.form` (as we did a `return { form }`). There, we'll use the client part of the API:
**src/routes/+page.svelte**
```svelte
<script lang="ts">
import { superForm } from 'sveltekit-superforms';
let { data } = $props();
// Client API:
const { form } = superForm(data.form);
</script>
<form method="POST">
<label for="name">Name</label>
<input type="text" name="name" bind:value={$form.name} />
<label for="email">E-mail</label>
<input type="email" name="email" bind:value={$form.email} />
<div><button>Submit</button></div>
</form>
```
The `superForm` function is used to create a form on the client, and `bind:value` is used to create a two-way binding between the form data and the input fields.
> Two notes: There should be only one `superForm` instance per form - its methods cannot be used in multiple forms. And don't forget the `name` attribute on the input fields! Unless you are using [nested data](/concepts/nested-data), they are required.
This is what the form should look like now:
<Form {data} bind:this={formComponent} />
### Debugging
We can see that the form has been populated with the default values. But let's add the debugging component [SuperDebug](/super-debug) to look behind the scenes:
**src/routes/+page.svelte**
```svelte
<script lang="ts">
import SuperDebug from 'sveltekit-superforms';
</script>
<SuperDebug data={$form} />
```
This should be displayed:
<SuperDebug data={$form} />
When editing the form fields (try in the form above), the data is automatically updated. The component also displays a copy button and the current page status in the right corner. There are many [configuration options](/super-debug) available.
### Posting data
In the form actions, defined in `+page.server.ts`, we'll use the `superValidate` function again, but now it should handle `FormData`. This can be done in several ways:
- Use the `request` parameter (which contains `FormData`)
- Use the `event` object (which contains the request)
- Use `FormData` directly, if you need to access it before calling `superValidate`.
The most common is to use `request`:
**src/routes/+page.server.ts**
{#if $settings.lib == 'json-schema'}
```ts
import { message } from 'sveltekit-superforms';
import { fail } from '@sveltejs/kit';
export const actions = {
default: async ({ request }) => {
// The adapter must be defined before superValidate for JSON Schema.
const adapter = schemasafe(schema);
const form = await superValidate(request, adapter);
console.log(form);
if (!form.valid) {
// Again, return { form } and things will just work.
return fail(400, { form });
}
// TODO: Do something with the validated form.data
// Display a success status message
return message(form, 'Form posted successfully!');
}
};
```
{:else if $settings.lib == 'class-validator' || $settings.lib == 'superstruct' || $settings.lib == 'arktype' || $settings.lib == '@vinejs/vine'}
```ts
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) {
// Again, return { form } and things will just work.
return fail(400, { form });
}
// TODO: Do something with the validated form.data
// Display a success status message
return message(form, 'Form posted successfully!');
}
};
```
{:else}
```ts
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) {
// Again, return { form } and things will just work.
return fail(400, { form });
}
// TODO: Do something with the validated form.data
// Display a success status message
return message(form, 'Form posted successfully!');
}
};
```
{/if}
Now we can post the form back to the server. Submit the form, and see what's happening on the server:
```ts
{
id: 'a3g9kke',
valid: false,
posted: true,
data: { name: 'Hello world!', email: '' },
errors: { email: [ 'Invalid email' ] }
}
```
This is the validation object returned from `superValidate`, containing the data needed to update the form:
| Property | Purpose |
| ----------- | -------------------------------------------------------------------------------------------------------- |
| **id** | Id for the schema, to handle [multiple forms](/concepts/multiple-forms) on the same page. |
| **valid** | Tells you whether the validation succeeded or not. Used on the server and in [events](/concepts/events). |
| **posted** | Tells you if the data was posted (in a form action) or not (in a load function). |
| **data** | The posted data, which should be returned to the client using `fail` if not valid. |
| **errors** | An object with all validation errors, in a structure reflecting the data. |
| **message** | (optional) Can be set as a [status message](/concepts/messages). |
There are some other properties as well, only being sent in the load function:
| Property | Purpose |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **constraints** | An object with [HTML validation constraints](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#using_built-in_form_validation), that can be spread on input fields. |
| **shape** | Used internally in error handling. |
You can modify any of these, and they will be updated on the client when you `return { form }`. There are a couple of helper functions for making this more convenient, like [message](/concepts/messages) and [setError](/concepts/error-handling).
### Displaying errors
Now we know that validation has failed and there are errors being sent to the client. We display these by adding properties to the destructuring assignment of `superForm`:
**src/routes/+page.svelte**
```svelte
<script lang="ts">
const { form, errors, constraints, message } = superForm(data.form);
// ^^^^^^ ^^^^^^^^^^^ ^^^^^^^
</script>
{#if $message}<h3>{$message}</h3>{/if}
<form method="POST">
<label for="name">Name</label>
<input
type="text"
name="name"
aria-invalid={$errors.name ? 'true' : undefined}
bind:value={$form.name}
{...$constraints.name} />
{#if $errors.name}<span class="invalid">{$errors.name}</span>{/if}
<label for="email">E-mail</label>
<input
type="email"
name="email"
aria-invalid={$errors.email ? 'true' : undefined}
bind:value={$form.email}
{...$constraints.email} />
{#if $errors.email}<span class="invalid">{$errors.email}</span>{/if}
<div><button>Submit</button></div>
</form>
<style>
.invalid {
color: red;
}
</style>
```
By including the `errors` store, we can display errors where appropriate, and through `constraints` we'll get browser validation even without JavaScript enabled. The `aria-invalid` attribute is used to [automatically focus](/concepts/error-handling#errorselector) on the first error field. And finally, we added a [status message](/concepts/messages) above the form to show if it was posted successfully.
We now have a fully working form, with convenient handling of data and validation both on the client and server!
There are no hidden DOM manipulations or other secrets; it's just HTML attributes and Svelte stores, so it works with server-side rendering. No JavaScript is required for the basics.
### Adding progressive enhancement
As a last step, let's add progressive enhancement, so users with JavaScript enabled will have a nicer experience. It's also required for enabling [client-side validation](/concepts/client-validation) and [events](/concepts/events), and of course to avoid reloading the page when the form is posted.
This is simply done with `enhance`, returned from `superForm`:
```svelte
<script lang="ts">
const { form, errors, constraints, message, enhance } = superForm(data.form);
// ^^^^^^^
</script>
<!-- Add to the form element: -->
<form method="POST" use:enhance>
```
Now the page won't fully reload when submitting, and we unlock lots of client-side features like timers for [loading spinners](/concepts/timers), [auto error focus](/concepts/error-handling#errorselector), [tainted fields](/concepts/tainted), etc, which you can read about under the Concepts section in the navigation.
The `use:enhance` action takes no arguments; instead, events are used to hook into the SvelteKit use:enhance parameters and more. Check out the [events page](/concepts/events) for details.
## Next steps
This concludes the tutorial! To learn the details, keep reading under the Concepts section in the navigation. A [status message](/concepts/messages) is very common to add, for example. Also, if you plan to use nested data (objects and arrays within the schema), read the [nested data](/concepts/nested-data) page carefully. The same goes for having [multiple forms on the same page](/concepts/multiple-forms).
When you're ready for something more advanced, check out the [CRUD tutorial](/crud), which shows how to make a fully working backend in about 150 lines of code.
Enjoy your Superforms!