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```ts
17ageValidators = [
18 {
19 triggers: ['change'] as const,
20 run: ({ value }: { value: number }) =>
21 value >= 13 ? undefined : 'You must be at least 13',
22 },
23 {
24 triggers: ['blur'] as const,
25 run: ({ value }: { value: number }) =>
26 value >= 0 ? undefined : 'Age cannot be negative',
27 },
28]
29```
30
31```html
32<ng-container
33 [tanstackField]="form"
34 name="age"
35 [validators]="ageValidators"
36 #field="field"
37>
38 <label>
39 Age
40 <input
41 type="number"
42 [name]="field.api.name"
43 [value]="field.api.value"
44 (blur)="field.api.handleBlur()"
45 (input)="field.api.handleChange($any($event).target.valueAsNumber)"
46 [attr.aria-invalid]="field.api.meta.isInvalid"
47 />
48 @for (error of field.api.errors; track error) {
49 <span role="alert">{{ error.message }}</span>
50 }
51 </label>
52</ng-container>
53```
54
55Additional controls include:
56
57- `runOnMount`: run once when the form is constructed or when a field or form
58 group first mounts.
59- `skipOnSubmit`: conditionally skip submit-time execution.
60- `triggerDebounceMs`: debounce change and blur execution.
61- `bailIfInvalid`: skip this and subsequent validators when an earlier one
62 failed.
63- trigger objects with `when`: enable a trigger conditionally.
64- `watchFields`: rerun a field validator when related fields trigger it.
65
66## Control when errors are visible
67
68Validation and presentation are separate. `errorVisibility` decides when
69field issues appear in `field.api.errors`:
70
71```ts
72import { injectForm } from '@tanstack/angular-form'
73
74form = injectForm({
75 defaultValues: { email: '' },
76 errorVisibility: ({ fieldState, state }) =>
77 fieldState.meta.isBlurred || state.submissionAttempts > 0,
78})
79```
80
81Use `field.api.meta.original.errors` for the unfiltered issues when debugging
82or building a custom visibility system.
83
84## Form-level validation
85
86A form validator can produce a form issue and route issues to typed field paths
87with `createErrorMap`:
88
89```ts
90import { injectForm, injectSelector } from '@tanstack/angular-form'
91
92form = injectForm({
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
115formErrors = injectSelector(this.form, (state) => state.errors)
116```
117
118`injectSelector` exposes form-level issues as an Angular signal. Lower-level
119integrations can subscribe to `form.atom` directly. Field-routed issues appear
120in the corresponding `field.api.errors`.
121
122## Asynchronous validation and debouncing
123
124`run` may return a promise. Put cheap synchronous checks first and use
125`bailIfInvalid` to avoid unnecessary requests:
126
127```ts
128usernameValidators = [
129 {
130 triggers: ['change'] as const,
131 run: ({ value }: { value: string }) =>
132 value.length >= 3 ? undefined : 'Use at least 3 characters',
133 },
134 {
135 triggers: ['change'] as const,
136 triggerDebounceMs: 500,
137 bailIfInvalid: true,
138 run: async ({ value }: { value: string }) => {
139 const available = await checkUsername(value)
140 return available ? undefined : 'That username is already taken'
141 },
142 },
143]
144```
145
146Pass this array to the field with `[validators]="usernameValidators"`.
147Submit validation always runs immediately, even when a trigger is debounced.
148`field.api.meta.isValidating` and `form.state.isValidating` expose pending
149work.
150
151## Standard Schema validation
152
153Any Standard Schema implementation can be supplied as `run`:
154
155```ts
156import { injectForm } from '@tanstack/angular-form'
157import { z } from 'zod'
158
159const accountSchema = z.object({
160 email: z.string().email(),
161 age: z.number().min(13),
162})
163
164form = injectForm({
165 defaultValues: { email: '', age: 0 },
166 validators: [
167 {
168 triggers: ['change'],
169 run: accountSchema,
170 },
171 ],
172})
173```
174
175Schema paths are routed to matching fields. Parsed outputs are available by
176validator index in `schemaOutputs` during submit, for example
177`schemaOutputs[0]`. `value` remains the form's raw editable state rather than
178the parsed output.
179
180For custom schema routing, call a schema's safe parse API inside `run` and pass
181its issues to the provided `parseIssues` helper.
182
183## Validate related fields
184
185Use `watchFields` when one field's validity depends on another:
186
187```ts
188import type { FieldValidators } from '@tanstack/angular-form'
189
190type DateFormValues = { startDate: string; endDate: string }
191
192endDateValidators = [
193 {
194 triggers: ['change', 'blur'],
195 watchFields: ['startDate'],
196 run: ({ value, formApi }) =>
197 value >= formApi.getFieldValue('startDate')
198 ? undefined
199 : 'End date must be on or after the start date',
200 },
201] satisfies FieldValidators<DateFormValues, 'endDate', string>
202```
203
204```html
205<ng-container
206 [tanstackField]="form"
207 name="endDate"
208 [validators]="endDateValidators"
209 #field="field"
210>
211 <input
212 type="date"
213 [name]="field.api.name"
214 [value]="field.api.value"
215 (blur)="field.api.handleBlur()"
216 (input)="field.api.handleChange($any($event).target.value)"
217 [attr.aria-invalid]="field.api.meta.isInvalid"
218 />
219</ng-container>
220```
221
222## Validate a scoped form group
223
224`TanStackFormGroup` creates a v2 group for one concrete section of a form. The
225directive exports its API as `formGroup`, and `fieldName` resolves a
226group-relative name to the concrete form path:
227
228```ts
229import { TanStackField, TanStackFormGroup } from '@tanstack/angular-form'
230import type { FormGroupValidators } from '@tanstack/angular-form'
231
232profileValidators = [
233 {
234 triggers: [],
235 run: ({ value }: { value: { name: string } }) =>
236 value.name.length >= 2 ? undefined : 'Enter a name',
237 },
238] satisfies FormGroupValidators<{ name: string }>
239
240submitGroup(event: SubmitEvent, group: { handleSubmit: () => unknown }) {
241 event.preventDefault()
242 void group.handleSubmit()
243}
244```
245
246```html
247<ng-container
248 [tanstackFormGroup]="form"
249 name="profile"
250 [validators]="profileValidators"
251 #profile="formGroup"
252>
253 <form (submit)="submitGroup($event, profile.api)">
254 <ng-container [tanstackField]="profile.api" name="name" #name="field">
255 <input
256 [name]="name.api.name"
257 [value]="name.api.value"
258 (input)="name.api.handleChange($any($event).target.value)"
259 />
260 </ng-container>
261
262 @for (error of profile.api.state.errors; track error) {
263 <span role="alert">{{ error.message }}</span>
264 }
265 <button type="submit">Continue</button>
266 </form>
267</ng-container>
268```
269
270Import both directives in the standalone component. Use a Form Group for a
271scoped section of one form; use reusable field mappings when a component must
272work with different concrete field paths.
273
274## Return errors from submission
275
276Endpoint validation belongs in `onSubmit`. Return
277`createValidationError(...)` to feed server issues back into normal form state:
278
279```ts
280form = injectForm({
281 defaultValues: { email: '' },
282 onSubmit: async ({ value, createValidationError }) => {
283 const result = await saveProfile(value)
284
285 if (!result.ok) {
286 return createValidationError({
287 form: 'Could not save the profile',
288 fields: { email: 'This email is already registered' },
289 })
290 }
291
292 return null
293 },
294})
295```
296
297## Prevent invalid submission
298
299`form.handleSubmit()` skips `onSubmit` when validation fails and resolves with
300the validation errors. `onSubmitInvalid` is currently available on form
301groups; root-form support is planned but not yet implemented. Select
302`canSubmit` and `isSubmitting` as Angular signals to reflect that state in the
303submit UI:
304
305```ts
306canSubmit = injectSelector(this.form, (state) => state.canSubmit)
307isSubmitting = injectSelector(this.form, (state) => state.isSubmitting)
308```
309
310```html
311<button type="submit" [disabled]="!canSubmit() || isSubmitting()">
312 {{ isSubmitting() ? 'Submitting…' : 'Submit' }}
313</button>
314```
315
316If a disabled submit button would hide useful validation feedback, keep it
317focusable with `aria-disabled` and let `handleSubmit()` report the issues.