Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

quick-start.md

114 lines2.7 KB

1---
2id: quick-start
3title: Quick Start
4---
5​
6TanStack Form is a headless, type-safe form library. It owns form state and
7validation while leaving markup, styling, and component choice to you.
8​
9Install the Svelte adapter:
10​
11```bash
12npm install @tanstack/svelte-form
13```
14​
15## Create a form
16​
17`createForm` requires an options function and form-level `defaultValues`. Their
18shape becomes the form's inferred value type.
19​
20```svelte
21<script lang="ts">
22 import { createForm } from '@tanstack/svelte-form'
23​
24 const form = createForm(() => ({
25 defaultValues: {
26 fullName: '',
27 age: 0,
28 },
29 onSubmit: async ({ value }) => {
30 console.log(value)
31 },
32 }))
33</script>
34​
35<form
36 onsubmit={(event) => {
37 event.preventDefault()
38 form.handleSubmit()
39 }}
41 <form.Field
42 name="fullName"
43 validators={[
44 {
45 triggers: ['change', 'blur'],
46 run: ({ value }) =>
47 value.trim() ? undefined : 'Enter your full name',
48 },
49 ]}
50 >
51 {#snippet children(field)}
52 <label>
53 Full name
54 <input
55 name={field.name}
56 value={field.value}
57 onblur={field.handleBlur}
58 oninput={(event) => field.handleChange(event.currentTarget.value)}
59 aria-invalid={field.meta.isInvalid}
60 />
61 {#each field.errors as error}
62 <span role="alert">{error.message}</span>
63 {/each}
64 </label>
65 {/snippet}
66 </form.Field>
67​
68 <form.Field
69 name="age"
70 validators={[
71 {
72 triggers: ['change'],
73 run: ({ value }) =>
74 value >= 13 ? undefined : 'You must be at least 13',
75 },
76 ]}
77 >
78 {#snippet children(field)}
79 <label>
80 Age
81 <input
82 name={field.name}
83 type="number"
84 value={field.value}
85 onblur={field.handleBlur}
86 oninput={(event) =>
87 field.handleChange(event.currentTarget.valueAsNumber)}
88 aria-invalid={field.meta.isInvalid}
89 />
90 </label>
91 {/snippet}
92 </form.Field>
93​
94 <form.Subscribe
95 selector={(state) => [state.canSubmit, state.isSubmitting] as const}
96 >
97 {#snippet children([canSubmit, isSubmitting])}
98 <button type="submit" disabled={!canSubmit || isSubmitting}>
99 {isSubmitting ? 'Saving…' : 'Save'}
100 </button>
101 {/snippet}
102 </form.Subscribe>
103</form>
104```
105​
106The important pieces are:
107​
108- `defaultValues` define the complete initial value and drive type inference.
109- `form.Field` subscribes to one field. Its child snippet exposes `field.value`,
110 `field.meta`, and event handlers.
111- Validators are ordered objects with a `run` function and explicit `triggers`.
112- `form.Subscribe` updates only its child snippet when the selected form state
113 changes.
114- `form.handleSubmit()` validates the form before calling `onSubmit`.