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

validation.md

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