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

validation.md

239 lines6.2 KB

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