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