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

validation.md

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