Open History to see the last commit
1---
2id: form-validation
3title: Form and Field Validation
4---
5
6TanStack Form supports synchronous, asynchronous, field-level, form-level, and
7Standard Schema validation. Every validator is an ordered object with a `run`
8implementation and explicit `triggers`.
9
10## Choose when validation runs
11
12Use `change` for immediate feedback and `blur` for feedback after leaving an
13input. Submission runs validators by default regardless of their configured
14change and blur triggers.
15
16```svelte
17<form.Field
18 name="age"
19 validators={[
20 {
21 triggers: ['change'],
22 run: ({ value }) =>
23 value >= 13 ? undefined : 'You must be at least 13',
24 },
25 {
26 triggers: ['blur'],
27 run: ({ value }) =>
28 value >= 0 ? undefined : 'Age cannot be negative',
29 },
30 ]}
31>
32 {#snippet children(field)}
33 <label>
34 Age
35 <input
36 name={field.name}
37 type="number"
38 value={field.value}
39 onblur={field.handleBlur}
40 oninput={(event) =>
41 field.handleChange(event.currentTarget.valueAsNumber)}
42 aria-invalid={field.meta.isInvalid}
43 />
44 {#each field.errors as error}
45 <span role="alert">{error.message}</span>
46 {/each}
47 </label>
48 {/snippet}
49</form.Field>
50```
51
52Additional controls include:
53
54- `runOnMount`: run once when the form is constructed or when a field or form
55 group first mounts.
56- `skipOnSubmit`: conditionally skip submit-time execution.
57- `triggerDebounceMs`: debounce change and blur execution.
58- `bailIfInvalid`: skip this and subsequent validators when an earlier one
59 failed.
60- trigger objects with `when`: enable a trigger conditionally.
61- `watchFields`: rerun a field validator when related fields trigger it.
62
63## Control when errors are visible
64
65Validation and presentation are separate. `errorVisibility` decides when field
66issues appear in `field.errors`:
67
68```svelte
69<script lang="ts">
70 import { createForm } from '@tanstack/svelte-form'
71
72 const form = createForm(() => ({
73 defaultValues: { email: '' },
74 errorVisibility: ({ fieldState, state }) =>
75 fieldState.meta.isBlurred || state.submissionAttempts > 0,
76 }))
77</script>
78```
79
80Use `field.meta.original.errors` for the unfiltered issues when debugging or
81building a custom visibility system.
82
83## Form-level validation
84
85A form validator can produce a form issue and route issues to typed field paths
86with `createErrorMap`:
87
88```svelte
89<script lang="ts">
90 import { createForm } from '@tanstack/svelte-form'
91
92 const form = createForm(() => ({
93 defaultValues: {
94 email: '',
95 phone: '',
96 },
97 validators: [
98 {
99 triggers: ['change'],
100 run: ({ value, createErrorMap }) => {
101 const errors = createErrorMap()
102
103 if (!value.email && !value.phone) {
104 errors.form = 'Provide an email address or phone number'
105 errors.fields.email = 'Email is required when phone is empty'
106 errors.fields.phone = 'Phone is required when email is empty'
107 }
108
109 return errors
110 },
111 },
112 ],
113 }))
114</script>
115```
116
117Use `form.Subscribe` to reactively select form-level issues from
118`form.state.errors`. Lower-level integrations can subscribe to `form.atom`.
119Field-routed issues appear in the corresponding `field.errors`.
120
121## Asynchronous validation and debouncing
122
123`run` may return a promise. Put cheap synchronous checks first and use
124`bailIfInvalid` to avoid unnecessary requests:
125
126```svelte
127<form.Field
128 name="username"
129 validators={[
130 {
131 triggers: ['change'],
132 run: ({ value }) =>
133 value.length >= 3 ? undefined : 'Use at least 3 characters',
134 },
135 {
136 triggers: ['change'],
137 triggerDebounceMs: 500,
138 bailIfInvalid: true,
139 run: async ({ value }) => {
140 const available = await checkUsername(value)
141 return available ? undefined : 'That username is already taken'
142 },
143 },
144 ]}
145>
146 {#snippet children(field)}
147 <input
148 name={field.name}
149 value={field.value}
150 oninput={(event) => field.handleChange(event.currentTarget.value)}
151 />
152 {/snippet}
153</form.Field>
154```
155
156Submit validation always runs immediately, even when a trigger is debounced.
157`field.meta.isValidating` and `form.state.isValidating` expose pending work.
158
159## Standard Schema validation
160
161Any Standard Schema implementation can be supplied as `run`:
162
163```svelte
164<script lang="ts">
165 import { createForm } from '@tanstack/svelte-form'
166 import { z } from 'zod'
167
168 const accountSchema = z.object({
169 email: z.string().email(),
170 age: z.number().min(13),
171 })
172
173 const form = createForm(() => ({
174 defaultValues: { email: '', age: 0 },
175 validators: [
176 {
177 triggers: ['change'],
178 run: accountSchema,
179 },
180 ],
181 }))
182</script>
183```
184
185Schema paths are routed to matching fields. Parsed outputs are available by
186validator index in `schemaOutputs` during submit, for example
187`schemaOutputs[0]`. `value` remains the form's raw editable state rather than
188the parsed output.
189
190For custom schema routing, call a schema's safe parse API inside `run` and pass
191its issues to the provided `parseIssues` helper.
192
193## Validate related fields
194
195Use `watchFields` when one field's validity depends on another:
196
197```svelte
198<form.Field
199 name="endDate"
200 validators={[
201 {
202 triggers: ['change', 'blur'],
203 watchFields: ['startDate'],
204 run: ({ value, formApi }) =>
205 value >= formApi.getFieldValue('startDate')
206 ? undefined
207 : 'End date must be on or after the start date',
208 },
209 ]}
210>
211 {#snippet children(field)}
212 <input
213 name={field.name}
214 type="date"
215 value={field.value}
216 onblur={field.handleBlur}
217 oninput={(event) => field.handleChange(event.currentTarget.value)}
218 aria-invalid={field.meta.isInvalid}
219 />
220 {/snippet}
221</form.Field>
222```
223
224## Return errors from submission
225
226Endpoint validation belongs in `onSubmit`. Return
227`createValidationError(...)` to feed server issues back into normal form state:
228
229```svelte
230<script lang="ts">
231 import { createForm } from '@tanstack/svelte-form'
232
233 const form = createForm(() => ({
234 defaultValues: { email: '' },
235 onSubmit: async ({ value, createValidationError }) => {
236 const result = await saveProfile(value)
237
238 if (!result.ok) {
239 return createValidationError({
240 form: 'Could not save the profile',
241 fields: { email: 'This email is already registered' },
242 })
243 }
244
245 return null
246 },
247 }))
248</script>
249```
250
251## Prevent invalid submission
252
253`form.handleSubmit()` skips `onSubmit` when validation fails and resolves with
254the validation errors. `onSubmitInvalid` is currently available on form groups;
255root-form support is planned but not yet implemented. Subscribe to `canSubmit`
256and `isSubmitting` to reflect that state in the submit UI:
257
258```svelte
259<form.Subscribe
260 selector={(state) => [state.canSubmit, state.isSubmitting]}
261>
262 {#snippet children([canSubmit, isSubmitting])}
263 <button type="submit" disabled={!canSubmit || isSubmitting}>
264 {isSubmitting ? 'Submitting…' : 'Submit'}
265 </button>
266 {/snippet}
267</form.Subscribe>
268```
269
270If a disabled submit button would hide useful validation feedback, keep it
271focusable with `aria-disabled` and let `handleSubmit()` report the issues.