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.isValid) {
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β
207It's worth mentioning that our `errors` array and the `errorMap` matches the types returned by the validators. This means that:
208β
209```angular-ts
210@Component({
211 selector: 'app-root',
212 standalone: true,
213 imports: [TanStackField],
214 template: `
215 <ng-container
216 [tanstackField]="form"
217 name="age"
218 [validators]="{
219 onChange: ageValidator
220 }"
221 #age="field"
222 >
223 <!-- ... -->
224 <!-- errorMap.onChange is type `{isOldEnough: false} | undefined` -->
225 <!-- meta.errors is type `Array<{isOldEnough: false} | undefined>` -->
226 @if (!age.api.state.meta.errorMap['onChange']?.isOldEnough) {
227 <em role="alert">The user is not old enough</em>
228 }
229 </ng-container>
230 `,
231})
232export class AppComponent {
233 ageValidator: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
234 value < 13 ? 'You must be 13 to make an account' : undefined
235β
236 // ...
237}
238```
239β
240## Validation at field level vs at form level
241β
242As 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.
243β
244Example:
245β
246```angular-ts
247@Component({
248 selector: 'app-root',
249 standalone: true,
250 imports: [TanStackField],
251 template: `
252 <div>
253 <ng-container [tanstackField]="form" name="age" #age="field">
254 <!-- ... -->
255 @if (formErrorMap().onChange) {
256 <div>
257 <em
258 >There was an error on the form: {{ formErrorMap().onChange }}</em
259 >
260 </div>
261 }
262 <!-- ... -->
263 </ng-container>
264 </div>
265 `,
266})
267export class AppComponent {
268 form = injectForm({
269 defaultValues: {
270 age: 0,
271 },
272 onSubmit({ value }) {
273 console.log(value)
274 },
275 validators: {
276 // Add validators to the form the same way you would add them to a field
277 onChange({ value }) {
278 if (value.age < 13) {
279 return 'Must be 13 or older to sign'
280 }
281 return undefined
282 },
283 },
284 })
285β
286 // Subscribe to the form's error map so that updates to it will render
287 formErrorMap = injectStore(this.form, (state) => state.errorMap)
288}
289```
290β
291### Setting field-level errors from the form's validators
292β
293You can set errors on the fields from the form's validators. One common use case for this is validating all the fields on submit by calling a single API endpoint in the form's `onSubmitAsync` validator.
294β
295```angular-ts
296@Component({
297 selector: 'app-root',
298 imports: [TanStackField],
299 template: `
300 <form (submit)="handleSubmit($event)">
301 <div>
302 <ng-container
303 [tanstackField]="form"
304 name="age"
305 #ageField="field"
306 >
307 <label [for]="ageField.api.name">Age:</label>
308 <input
309 type="number"
310 [name]="ageField.api.name"
311 [value]="ageField.api.state.value"
312 (blur)="ageField.api.handleBlur()"
313 (input)="ageField.api.handleChange($any($event).target.valueAsNumber)"
314 />
315 @if (ageField.api.state.meta.errors.length > 0) {
316 <em role="alert">{{ ageField.api.state.meta.errors.join(', ') }}</em>
317 }
318 </ng-container>
319 </div>
320 <button type="submit">Submit</button>
321 </form>
322 `,
323})
324β
325export class AppComponent {
326 form = injectForm({
327 defaultValues: {
328 age: 0,
329 socials: [],
330 details: {
331 email: '',
332 },
333 },
334 validators: {
335 onSubmitAsync: async ({ value }) => {
336 // Validate the value on the server
337 const hasErrors = await verifyDataOnServer(value)
338 if (hasErrors) {
339 return {
340 form: 'Invalid data', // The `form` key is optional
341 fields: {
342 age: 'Must be 13 or older to sign',
343 // Set errors on nested fields with the field's name
344 'socials[0].url': 'The provided URL does not exist',
345 'details.email': 'An email is required',
346 },
347 };
348 }
349β
350 return null;
351 },
352 },
353 });
354β
355 handleSubmit(event: SubmitEvent) {
356 event.preventDefault();
357 event.stopPropagation();
358 this.form.handleSubmit();
359 }
360}
361```
362β
363> Something worth mentioning is that if you have a form validation function that returns an error, that error may be overwritten by the field-specific validation.
364>
365> This means that:
366>
367> ```angular-ts
368> @Component({
369> selector: 'app-root',
370> standalone: true,
371> imports: [TanStackField],
372> template: `
373> <div>
374> <ng-container
375> [tanstackField]="form"
376> name="age"
377> #ageField="field"
378> [validators]="{
379> onChange: fieldValidator
380> }"
381> >
382> <input type="number" [value]="ageField.api.state.value"
383> (input)="ageField.api.handleChange($any($event).target.valueAsNumber)"
384> />
385> @if (ageField.api.state.meta.errors.length > 0) {
386> <em role="alert">{{ ageField.api.state.meta.errors.join(', ') }}</em>
387> }
388> </ng-container>
389> </div>
390> `,
391> })
392> export class AppComponent {
393> form = injectForm({
394> defaultValues: {
395> age: 0,
396> },
397> validators: {
398> onChange: ({ value }) => {
399> return {
400> fields: {
401> age: value.age < 12 ? 'Too young!' : undefined,
402> },
403> };
404> },
405> },
406> });
407>
408> fieldValidator: FieldValidateFn<any, any, number> = ({ value }) =>
409> value % 2 === 0 ? 'Must be odd!' : undefined;
410> }
411>
412> ```
413>
414> Will only show `'Must be odd!` even if the 'Too young!' error is returned by the form-level validation.
415β
416## Asynchronous Functional Validation
417β
418While 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.
419β
420To do this, we have dedicated `onChangeAsync`, `onBlurAsync`, and other methods that can be used to validate against:
421β
422```angular-ts
423@Component({
424 selector: 'app-root',
425 standalone: true,
426 imports: [TanStackField],
427 template: `
428 <ng-container
429 [tanstackField]="form"
430 name="age"
431 [validators]="{ onChangeAsync: ageValidator }"
432 #age="field"
433 >
434 <label [for]="age.api.name">Last Name:</label>
435 <input
436 [id]="age.api.name"
437 [name]="age.api.name"
438 [value]="age.api.state.value"
439 type="number"
440 (input)="age.api.handleChange($any($event).target.valueAsNumber)"
441 />
442 @if (age.api.state.meta.errors) {
443 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
444 }
445 </ng-container>
446 `,
447})
448export class AppComponent {
449 ageValidator: FieldValidateAsyncFn<any, string, number> = async ({
450 value,
451 }) => {
452 await new Promise((resolve) => setTimeout(resolve, 1000))
453 return value < 13 ? 'You must be 13 to make an account' : undefined
454 }
455β
456 // ...
457}
458```
459β
460Synchronous and Asynchronous validations can coexist. For example, it is possible to define both `onBlur` and `onBlurAsync` on the same field:
461β
462```angular-ts
463@Component({
464 selector: 'app-root',
465 standalone: true,
466 imports: [TanStackField],
467 template: `
468 <ng-container
469 [tanstackField]="form"
470 name="age"
471 [validators]="{ onBlur: ensureAge13, onBlurAsync: ensureOlderAge }"
472 #age="field"
473 >
474 <label [for]="age.api.name">Last Name:</label>
475 <input
476 [id]="age.api.name"
477 [name]="age.api.name"
478 [value]="age.api.state.value"
479 type='number'
480 (blur)="age.api.handleBlur()"
481 (input)="age.api.handleChange($any($event).target.value)"
482 />
483 @if (age.api.state.meta.errors) {
484 <em role="alert">{{ age.api.state.meta.errors.join(', ') }}</em>
485 }
486 </ng-container>
487 `,
488})
489export class AppComponent {
490 ensureAge13: FieldValidateFn<any, any, any, any, number> = ({ value }) =>
491 value < 13 ? 'You must be at least 13' : undefined
492β
493 ensureOlderAge: FieldValidateAsyncFn<any, string, number> = async ({
494 value,
495 }) => {
496 const currentAge = await fetchCurrentAgeOnProfile()
497 return value < currentAge ? 'You can only increase the age' : undefined
498 }
499β
500 // ...
501}
502```
503β
504The 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.
505β
506### Built-in Debouncing
507β
508While 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.
509β
510Instead, we enable an easy method for debouncing your `async` calls by adding a single property:
511β
512```angular-html
513<ng-container
514 [tanstackField]="form"
515 name="age"
516 asyncDebounceMs={500}
517 [validators]="{ onChangeAsync: someValidator }"
518 #age="field"
519>
520 <!-- ... -->
521</ng-container>
522```
523β
524This will debounce every async call with a 500ms delay. You can even override this property on a per-validation property:
525β
526```angular-html
527<ng-container
528 [tanstackField]="form"
529 name="age"
530 [validators]="{
531 onChangeAsyncDebounceMs: 1500,
532 onChangeAsync: someValidator,
533 onBlurAsync: otherValidator
534 }"
535 #age="field"
536>
537 <!-- ... -->
538</ng-container>
539```
540β
541> This will run `onChangeAsync` every 1500ms while `onBlurAsync` will run every 500ms.
542β
543## Validation through Schema Libraries
544β
545While functions provide more flexibility and customization over your validation, they can be a bit verbose. To help solve this, there are libraries that provide schema-based validation to make shorthand and type-strict validation substantially easier. You can also define a single schema for your entire form and pass it to the form level, errors will be automatically propagated to the fields.
546β
547### Standard Schema Libraries
548β
549TanStack Form natively supports all libraries following the [Standard Schema specification](https://github.com/standard-schema/standard-schema), most notably:
550β
551- [Zod](https://zod.dev/)
552- [Valibot](https://valibot.dev/)
553- [ArkType](https://arktype.io/)
554β
555_Note:_ make sure to use the latest version of the schema libraries as older versions might not support Standard Schema yet.
556β
557> Validation will not provide you with transformed values. See [submission handling](./submission-handling.md) for more information.
558β
559To use schemas from these libraries you can pass them to the `validators` props as you would do with a custom function:
560β
561```angular-ts
562import { z } from 'zod'
563β
564@Component({
565 selector: 'app-root',
566 standalone: true,
567 imports: [TanStackField],
568 template: `
569 <ng-container
570 [tanstackField]="form"
571 name="age"
572 [validators]="{
573 onChange: z.number().gte(13, 'You must be 13 to make an account'),
574 }"
575 #age="field"
576 >
577 <!-- ... -->
578 </ng-container>
579 `,
580})
581export class AppComponent {
582 form = injectForm({
583 // ...
584 })
585β
586 z = z
587β
588 // ...
589}
590```
591β
592Async validations on form and field level are supported as well:
593β
594```angular-ts
595@Component({
596 selector: 'app-root',
597 standalone: true,
598 imports: [TanStackField],
599 template: `
600 <ng-container
601 [tanstackField]="form"
602 name="age"
603 [validators]="{
604 onChange: z.number().gte(13, 'You must be 13 to make an account'),
605 onChangeAsyncDebounceMs: 500,
606 onChangeAsync: increaseAge
607 }"
608 #age="field"
609 >
610 <!-- ... -->
611 </ng-container>
612 `,
613})
614export class AppComponent {
615 increaseAge = z.number().refine(
616 async (value) => {
617 const currentAge = await fetchCurrentAgeOnProfile()
618 return value >= currentAge
619 },
620 {
621 message: 'You can only increase the age',
622 },
623 )
624β
625 // ...
626}
627```
628β
629If you need even more control over your Standard Schema validation, you can combine a Standard Schema with a callback function like so:
630β
631```angular-ts
632@Component({
633 selector: 'app-root',
634 standalone: true,
635 imports: [TanStackField],
636 template: `
637 <ng-container
638 [tanstackField]="form"
639 name="age"
640 [validators]="{ onChangeAsync: ageValidator }"
641 #age="field"
642 >
643 <!-- ... -->
644 </ng-container>
645 `,
646})
647export class AppComponent {
648 ageValidator: FieldValidateAsyncFn<any, string, number> = async ({
649 value,
650 fieldApi,
651 }) => {
652 const errors = fieldApi.parseValueWithSchema(
653 z.number().gte(13, 'You must be 13 to make an account'),
654 )
655 if (errors) return errors
656β
657 // continue with your validation
658 }
659β
660 // ...
661}
662```
663β
664## Preventing invalid forms from being submitted
665β
666The `onChange`, `onBlur` etc... callbacks are also run when the form is submitted and the submission is blocked if the form is invalid.
667β
668The 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).
669β
670You 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).
671β
672```angular-ts
673@Component({
674 selector: 'app-root',
675 standalone: true,
676 imports: [TanStackField],
677 template: `
678 <!-- ... -->
679 <button type="submit" [disabled]="!canSubmit()">
680 {{ isSubmitting() ? '...' : 'Submit' }}
681 </button>
682 `,
683})
684export class AppComponent {
685 canSubmit = injectStore(this.form, (state) => state.canSubmit)
686 isSubmitting = injectStore(this.form, (state) => state.isSubmitting)
687β
688 // ...
689}
690```
691β
692To prevent the form from being submitted before any interaction, combine `canSubmit` with `isPristine` flags. A simple condition like `!canSubmit || isPristine` effectively disables submissions until the user has made changes.