Open History to see the last commit
1---
2id: form-validation
3title: Form and Field Validation
4---
5β
6At the core of TanStack Form's functionalities is the concept of validation. TanStack Form makes validation highly customizable:
7β
8- You can control when to perform the validation (on change, on input, on blur, on submit...)
9- Validation rules can be defined at the field level or at the form level
10- Validation can be synchronous or asynchronous (for example, as a result of an API call)
11β
12## When is validation performed?
13β
14It's up to you! The `[tanstackField]` directive accepts some callbacks as props such as `onChange` or `onBlur`. Those callbacks are passed the current value of the field, as well as the fieldAPI object, so that you can perform the validation. If you find a validation error, simply return the error message as string and it will be available in `field.api.state.meta.errors`.
15β
16Here is an example:
17β
18```angular-ts
19@Component({
20 selector: 'app-root',
21 standalone: true,
22 imports: [TanStackField],
23 template: `
24 <ng-container
25 [tanstackField]="form"
26 name="age"
27 [validators]="{
28 onChange: ageValidator
29 }"
30 #age="field"
31 >
32 <label [for]="age.api.name">Age:</label>
33 <input
34 [id]="age.api.name"
35 [name]="age.api.name"
36 [value]="age.api.state.value"
37 type="number"
38 (input)="age.api.handleChange($any($event).target.valueAsNumber)"
39 />
40 @if (age.api.state.meta.errors) {
41 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
42 }
43 </ng-container>
44 `,
45})
46export class AppComponent {
47 ageValidator: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
48 value < 13 ? 'You must be 13 to make an account' : undefined
49β
50 // ...
51}
52```
53β
54In the example above, the validation is done at each keystroke (`onChange`). If, instead, we wanted the validation to be done when the field is blurred, we would change the code above like so:
55β
56```angular-ts
57@Component({
58 selector: 'app-root',
59 standalone: true,
60 imports: [TanStackField],
61 template: `
62 <ng-container
63 [tanstackField]="form"
64 name="age"
65 [validators]="{
66 onBlur: ageValidator
67 }"
68 #age="field"
69 >
70 <label [for]="age.api.name">Age:</label>
71 <!-- We always need to implement onChange, so that TanStack Form receives the changes -->
72 <!-- Listen to the onBlur event on the field -->
73 <input
74 [id]="age.api.name"
75 [name]="age.api.name"
76 [value]="age.api.state.value"
77 type="number"
78 (blur)='age.api.handleBlur()'
79 (input)="age.api.handleChange($any($event).target.valueAsNumber)"
80 />
81 @if (age.api.state.meta.errors) {
82 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
83 }
84 </ng-container>
85 `,
86})
87export class AppComponent {
88 ageValidator: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
89 value < 13 ? 'You must be 13 to make an account' : undefined
90β
91 // ...
92}
93```
94β
95So you can control when the validation is done by implementing the desired callback. You can even perform different pieces of validation at different times:
96β
97```angular-ts
98@Component({
99 selector: 'app-root',
100 standalone: true,
101 imports: [TanStackField],
102 template: `
103 <ng-container
104 [tanstackField]="form"
105 name="age"
106 [validators]="{
107 onChange: ageValidator,
108 onBlur: minimumAgeValidator
109 }"
110 #age="field"
111 >
112 <label [for]="age.api.name">Age:</label>
113 <!-- We always need to implement onChange, so that TanStack Form receives the changes -->
114 <!-- Listen to the onBlur event on the field -->
115 <input
116 [id]="age.api.name"
117 [name]="age.api.name"
118 [value]="age.api.state.value"
119 type="number"
120 (blur)="age.api.handleBlur()"
121 (input)="age.api.handleChange($any($event).target.valueAsNumber)"
122 />
123 @if (age.api.state.meta.errors) {
124 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
125 }
126 </ng-container>
127 `,
128})
129export class AppComponent {
130 ageValidator: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
131 value < 13 ? 'You must be 13 to make an account' : undefined
132β
133 minimumAgeValidator: FieldValidateFn<any, any, any, any, number> = ({
134 value,
135 }) => (value < 0 ? 'Invalid value' : undefined)
136β
137 // ...
138}
139```
140β
141In the example above, we are validating different things on the same field at different times (at each keystroke and when blurring the field). Since `field.state.meta.errors` is an array, all the relevant errors at a given time are displayed. You can also use `field.state.meta.errorMap` to get errors based on _when_ the validation was done (onChange, onBlur etc...). More info about displaying errors below.
142β
143## Displaying Errors
144β
145Once you have your validation in place, you can map the errors from an array to be displayed in your UI:
146β
147```angular-ts
148@Component({
149 selector: 'app-root',
150 standalone: true,
151 imports: [TanStackField],
152 template: `
153 <ng-container
154 [tanstackField]="form"
155 name="age"
156 [validators]="{
157 onChange: ageValidator
158 }"
159 #age="field"
160 >
161 <!-- ... -->
162 @if (age.api.state.meta.errors) {
163 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
164 }
165 </ng-container>
166 `,
167})
168export class AppComponent {
169 ageValidator: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
170 value < 13 ? 'You must be 13 to make an account' : undefined
171β
172 // ...
173}
174```
175β
176Or use the `errorMap` property to access the specific error you're looking for:
177β
178```angular-ts
179@Component({
180 selector: 'app-root',
181 standalone: true,
182 imports: [TanStackField],
183 template: `
184 <ng-container
185 [tanstackField]="form"
186 name="age"
187 [validators]="{
188 onChange: ageValidator
189 }"
190 #age="field"
191 >
192 <!-- ... -->
193 @if (age.api.state.meta.errorMap['onChange']) {
194 <em role="alert">{{ age.api.state.meta.errorMap['onChange'] }}</em>
195 }
196 </ng-container>
197 `,
198})
199export class AppComponent {
200 ageValidator: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
201 value < 13 ? 'You must be 13 to make an account' : undefined
202β
203 // ...
204}
205```
206β
207## Validation at field level vs at form level
208β
209As shown above, each `[tanstackField]` accepts its own validation rules via the `onChange`, `onBlur` etc... callbacks. It is also possible to define validation rules at the form level (as opposed to field by field) by passing similar callbacks to the `injectForm()` function.
210β
211Example:
212β
213```angular-ts
214@Component({
215 selector: 'app-root',
216 standalone: true,
217 imports: [TanStackField],
218 template: `
219 <div>
220 <ng-container [tanstackField]="form" name="age" #age="field">
221 <!-- ... -->
222 @if (formErrorMap().onChange) {
223 <div>
224 <em
225 >There was an error on the form: {{ formErrorMap().onChange }}</em
226 >
227 </div>
228 }
229 <!-- ... -->
230 </ng-container>
231 </div>
232 `,
233})
234export class AppComponent {
235 form = injectForm({
236 defaultValues: {
237 age: 0,
238 },
239 onSubmit({ value }) {
240 console.log(value)
241 },
242 validators: {
243 // Add validators to the form the same way you would add them to a field
244 onChange({ value }) {
245 if (value.age < 13) {
246 return 'Must be 13 or older to sign'
247 }
248 return undefined
249 },
250 },
251 })
252β
253 // Subscribe to the form's error map so that updates to it will render
254 formErrorMap = injectStore(this.form, (state) => state.errorMap)
255}
256```
257β
258## Asynchronous Functional Validation
259β
260While we suspect most validations will be synchronous, there are many instances where a network call or some other async operation would be useful to validate against.
261β
262To do this, we have dedicated `onChangeAsync`, `onBlurAsync`, and other methods that can be used to validate against:
263β
264```angular-ts
265@Component({
266 selector: 'app-root',
267 standalone: true,
268 imports: [TanStackField],
269 template: `
270 <ng-container
271 [tanstackField]="form"
272 name="age"
273 [validators]="{ onChangeAsync: ageValidator }"
274 #age="field"
275 >
276 <label [for]="age.api.name">Last Name:</label>
277 <input
278 [id]="age.api.name"
279 [name]="age.api.name"
280 [value]="age.api.state.value"
281 type="number"
282 (input)="age.api.handleChange($any($event).target.valueAsNumber)"
283 />
284 @if (age.api.state.meta.errors) {
285 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
286 }
287 </ng-container>
288 `,
289})
290export class AppComponent {
291 ageValidator: FieldValidateAsyncFn<any, any, any, any, number> = async ({
292 value,
293 }) => {
294 await new Promise((resolve) => setTimeout(resolve, 1000))
295 return value < 13 ? 'You must be 13 to make an account' : undefined
296 }
297β
298 // ...
299}
300```
301β
302Synchronous and Asynchronous validations can coexist. For example, it is possible to define both `onBlur` and `onBlurAsync` on the same field:
303β
304```angular-ts
305@Component({
306 selector: 'app-root',
307 standalone: true,
308 imports: [TanStackField],
309 template: `
310 <ng-container
311 [tanstackField]="form"
312 name="age"
313 [validators]="{ onBlur: ensureAge13, onBlurAsync: ensureOlderAge }"
314 #age="field"
315 >
316 <label [for]="age.api.name">Last Name:</label>
317 <input
318 [id]="age.api.name"
319 [name]="age.api.name"
320 [value]="age.api.state.value"
321 type='number'
322 (blur)="age.api.handleBlur()"
323 (input)="age.api.handleChange($any($event).target.value)"
324 />
325 @if (age.api.state.meta.errors) {
326 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
327 }
328 </ng-container>
329 `,
330})
331export class AppComponent {
332 ensureAge13: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
333 value < 13 ? 'You must be at least 13' : undefined
334β
335 ensureOlderAge: FieldValidateAsyncFn<any, any, any, any, number> = async ({
336 value,
337 }) => {
338 const currentAge = await fetchCurrentAgeOnProfile()
339 return value < currentAge ? 'You can only increase the age' : undefined
340 }
341β
342 // ...
343}
344```
345β
346The synchronous validation method (`onBlur`) is run first and the asynchronous method (`onBlurAsync`) is only run if the synchronous one (`onBlur`) succeeds. To change this behaviour, set the `asyncAlways` option to `true`, and the async method will be run regardless of the result of the sync method.
347β
348### Built-in Debouncing
349β
350While async calls are the way to go when validating against the database, running a network request on every keystroke is a good way to DDOS your database.
351β
352Instead, we enable an easy method for debouncing your `async` calls by adding a single property:
353β
354```angular-html
355<ng-container
356 [tanstackField]="form"
357 name="age"
358 asyncDebounceMs={500}
359 [validators]="{ onChangeAsync: someValidator }"
360 #age="field"
361>
362 <!-- ... -->
363</ng-container>
364```
365β
366This will debounce every async call with a 500ms delay. You can even override this property on a per-validation property:
367β
368```angular-html
369<ng-container
370 [tanstackField]="form"
371 name="age"
372 [validators]="{
373 onChangeAsyncDebounceMs: 1500,
374 onChangeAsync: someValidator,
375 onBlurAsync: otherValidator
376 }"
377 #age="field"
378>
379 <!-- ... -->
380</ng-container>
381```
382β
383> This will run `onChangeAsync` every 1500ms while `onBlurAsync` will run every 500ms.
384β
385## Adapter-Based Validation (Zod, Yup, Valibot)
386β
387While functions provide more flexibility and customization over your validation, they can be a bit verbose. To help solve this, there are libraries like [Valibot](https://valibot.dev/), [Yup](https://github.com/jquense/yup), and [Zod](https://zod.dev/) that provide schema-based validation to make shorthand and type-strict validation substantially easier.
388β
389Luckily, we support all of these libraries through official adapters:
390β
391```bash
392$ npm install @tanstack/zod-form-adapter zod
393# or
394$ npm install @tanstack/yup-form-adapter yup
395# or
396$ npm install @tanstack/valibot-form-adapter valibot
397```
398β
399Once done, we can add the adapter to the `validator` property on the form or field:
400β
401```angular-ts
402import { zodValidator } from '@tanstack/zod-form-adapter'
403import { z } from 'zod'
404β
405@Component({
406 selector: 'app-root',
407 standalone: true,
408 imports: [TanStackField],
409 template: `
410 <ng-container
411 [tanstackField]="form"
412 name="age"
413 [validators]="{
414 onChange: z.number().gte(13, 'You must be 13 to make an account'),
415 }"
416 #age="field"
417 >
418 <!-- ... -->
419 </ng-container>
420 `,
421})
422export class AppComponent {
423 form = injectForm({
424 // Either add the validator here or on `Field`
425 validatorAdapter: zodValidator(),
426 // ...
427 })
428β
429 z = z
430β
431 // ...
432}
433```
434β
435These adapters also support async operations using the proper property names:
436β
437```angular-ts
438@Component({
439 selector: 'app-root',
440 standalone: true,
441 imports: [TanStackField],
442 template: `
443 <ng-container
444 [tanstackField]="form"
445 name="age"
446 [validators]="{
447 onChange: z.number().gte(13, 'You must be 13 to make an account'),
448 onChangeAsyncDebounceMs: 500,
449 onChangeAsync: increaseAge
450 }"
451 #age="field"
452 >
453 <!-- ... -->
454 </ng-container>
455 `,
456})
457export class AppComponent {
458 increaseAge = z.number().refine(
459 async (value) => {
460 const currentAge = await fetchCurrentAgeOnProfile()
461 return value >= currentAge
462 },
463 {
464 message: 'You can only increase the age',
465 },
466 )
467β
468 // ...
469}
470```
471β
472## Preventing invalid forms from being submitted
473β
474The `onChange`, `onBlur` etc... callbacks are also run when the form is submitted and the submission is blocked if the form is invalid.
475β
476The form state object has a `canSubmit` flag that is false when any field is invalid and the form has been touched (`canSubmit` is true until the form has been touched, even if some fields are "technically" invalid based on their `onChange`/`onBlur` props).
477β
478You can subscribe to it via `injectStore` and use the value in order to, for example, disable the submit button when the form is invalid (in practice, disabled buttons are not accessible, use `aria-disabled` instead).
479β
480```angular-ts
481@Component({
482 selector: 'app-root',
483 standalone: true,
484 imports: [TanStackField],
485 template: `
486 <!-- ... -->
487 <button type="submit" [disabled]="!canSubmit()">
488 {{ isSubmitting() ? '...' : 'Submit' }}
489 </button>
490 `,
491})
492export class AppComponent {
493 canSubmit = injectStore(this.form, (state) => state.canSubmit)
494 isSubmitting = injectStore(this.form, (state) => state.isSubmitting)
495β
496 // ...
497}
498```