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