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- You can control when to perform the validation (on change, on input, on blur, on submit...)
8- Validation rules can be defined at the field level or at the form level
9- Validation can be synchronous or asynchronous (for example as a result of an API call)
10β
11β
12## When is validation performed?
13β
14It's up to you! The `<Field />` component 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.state.meta.errors`.
15β
16Here is an example:
17β
18```tsx
19<form.Field
20 name="age"
21 validators={{
22 onChange: val => val < 13 ? "You must be 13 to make an account" : undefined
23 }}
24>
25 {field => (
26 <>
27 <label htmlFor={field.name}>Age:</label>
28 <input
29 name={field.name}
30 value={field.state.value}
31 type="number"
32 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
33 />
34 {field.state.meta.errors ? <em role="alert">{field.state.meta.errors.join(', ')}</em> : null}
35 </>
36 )}
37</form.Field>
38```
39β
40In 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:
41β
42```tsx
43<form.Field
44 name="age"
45 validators={{
46 onBlur: val => val < 13 ? "You must be 13 to make an account" : undefined
47 }}
48>
49 {field => (
50 <>
51 <label htmlFor={field.name}>Age:</label>
52 <input
53 name={field.name}
54 value={field.state.value}
55 type="number"
56 // Listen to the onBlur event on the field
57 onBlur={field.handleBlur}
58 // We always need to implement onChange, so that TanStack Form receives the changes
59 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
60 />
61 {field.state.meta.errors ? <em role="alert">{field.state.meta.errors.join(', ')}</em> : null}
62 </>
63 )}
64</form.Field>
65```
66β
67So you can control when the validation is done by implementing the desired callback. You can even perform different pieces of validation at different times:
68β
69```tsx
70<form.Field
71 name="age"
72 validators={{
73 onChange: val => val < 13 ? "You must be 13 to make an account" : undefined,
74 onBlur: (val) => (val < 0 ? "Invalid value" : undefined)
75 }}
76>
77 {field => (
78 <>
79 <label htmlFor={field.name}>Age:</label>
80 <input
81 name={field.name}
82 value={field.state.value}
83 type="number"
84 // Listen to the onBlur event on the field
85 onBlur={field.handleBlur}
86 // We always need to implement onChange, so that TanStack Form receives the changes
87 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
88 />
89 {field.state.meta.errors ? <em role="alert">{field.state.meta.errors.join(', ')}</em> : null}
90 </>
91 )}
92</form.Field>
93```
94β
95In 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.
96β
97## Displaying Errors
98β
99Once you have your validation in place, you can map the errors from an array to be displayed in your UI:
100β
101```tsx
102<form.Field
103 name="age"
104 validators={{
105 onChange: val => val < 13 ? "You must be 13 to make an account" : undefined
106 }}
107>
108 {(field) => {
109 return (
110 <>
111 {/* ... */}
112 {field.state.meta.errors ? (
113 <em>{field.state.meta.errors}</em>
114 ) : null}
115 </>
116 );
117 }}
118</form.Field>
119```
120β
121Or use the `errorMap` property to access the specific error you're looking for:
122β
123```tsx
124<form.Field
125 name="age"
126 validators={{
127 onChange: val => val < 13 ? "You must be 13 to make an account" : undefined
128 }}
129>
130 {(field) => (
131 <>
132 {/* ... */}
133 {field.state.meta.errorMap['onChange'] ? (
134 <em>{field.state.meta.errorMap['onChange']}</em>
135 ) : null}
136 </>
137 )}
138</form.Field>
139```
140β
141## Validation at field level vs at form level
142β
143As shown above, each `<Field>` 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 `useForm()` hook.
144β
145Example:
146β
147```tsx
148export default function App() {
149 const form = useForm({
150 defaultValues: {
151 age: 0,
152 },
153 onSubmit: async ({ value }) => {
154 console.log(value);
155 },
156 validators: {
157 // Add validators to the form the same way you would add them to a field
158 onChange({ value }) {
159 if (value.age < 13) {
160 return "Must be 13 or older to sign";
161 }
162 },
163 },
164 });
165β
166 // Subscribe to the form's error map so that updates to it will render
167 // alternately, you can use `form.Subscribe`
168 const formErrorMap = form.useStore((state) => state.errorMap);
169β
170 return (
171 <div>
172 {/* ... */}
173 {formErrorMap.onChange ? (
174 <div>
175 <em>There was an error on the form: {formErrorMap.onChange}</em>
176 </div>
177 ) : null}
178 {/* ... */}
179 </div>
180 );
181}
182```
183β
184β
185## Asynchronous Functional Validation
186β
187While we suspect most validations will be synchronous, there's many instances where a network call or some other async operation would be useful to validate against.
188β
189To do this, we have dedicated `onChangeAsync`, `onBlurAsync`, and other methods that can be used to validate against:
190β
191```tsx
192<form.Field
193 name="age"
194 validators={{
195 onChangeAsync: async (value) => {
196 await new Promise((resolve) => setTimeout(resolve, 1000));
197 return (
198 value < 13 ? "You must be 13 to make an account" : undefined
199 );
200 }
201 }}
202>
203 {field => (
204 <>
205 <label htmlFor={field.name}>Age:</label>
206 <input
207 name={field.name}
208 value={field.state.value}
209 type="number"
210 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
211 />
212 {field.state.meta.errors ? <em role="alert">{field.state.meta.errors.join(', ')}</em> : null}
213 </>
214 )}
215</form.Field>
216```
217β
218Synchronous and Asynchronous validations can coexist. For example it is possible to define both `onBlur` and `onBlurAsync` on the same field:
219β
220```tsx
221<form.Field
222 name="age"
223 validators={{
224 onBlur: (value) => value < 13 ? "You must be at least 13" : undefined,
225 onBlurAsync: async (value) => {
226 const currentAge = await fetchCurrentAgeOnProfile();
227 return (
228 value < currentAge ? "You can only increase the age" : undefined
229 );
230 }
231 }}
232>
233 {field => (
234 <>
235 <label htmlFor={field.name}>Age:</label>
236 <input
237 name={field.name}
238 value={field.state.value}
239 type="number"
240 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
241 />
242 {field.state.meta.errors ? <em role="alert">{field.state.meta.errors.join(', ')}</em> : null}
243 </>
244 )}
245</form.Field>
246```
247β
248The 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.
249β
250β
251### Built-in Debouncing
252β
253While 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.
254β
255Instead, we enable an easy method for debouncing your `async` calls by adding a single property:
256β
257```tsx
258<form.Field
259 name="age"
260 asyncDebounceMs={500}
261 validators={{
262 onChangeAsync={async (value) => {
263 // ...
264 }
265 }}
266 children={(field) => {
267 return (
268 <>
269 {/* ... */}
270 </>
271 );
272 }}
273/>
274```
275β
276This will debounce every async call with a 500ms delay. You can even override this property on a per-validation property:
277β
278```tsx
279<form.Field
280 name="age"
281 asyncDebounceMs={500}
282 validators={{
283 onChangeAsyncDebounceMs: 1500,
284 onChangeAsync: async (value) => {
285 // ...
286 },
287 onBlurAsync: async (value) => {
288 // ...
289 }
290 }}
291 children={(field) => {
292 return (
293 <>
294 {/* ... */}
295 </>
296 );
297 }}
298/>
299```
300β
301> This will run `onChangeAsync` every 1500ms while `onBlurAsync` will run every 500ms.
302β
303β
304## Adapter-Based Validation (Zod, Yup, Valibot)
305β
306While 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.
307β
308Luckily, we support all of these libraries through official adapters:
309β
310```bash
311$ npm install @tanstack/zod-form-adapter zod
312# or
313$ npm install @tanstack/yup-form-adapter yup
314# or
315$ npm install @tanstack/valibot-form-adapter valibot
316```
317β
318Once done, we can add the adapter to the `validator` property on the form or field:
319β
320```tsx
321import { zodValidator } from "@tanstack/zod-form-adapter";
322import { z } from "zod";
323β
324// ...
325β
326const form = useForm({
327 // Either add the validator here or on `Field`
328 validatorAdapter: zodValidator,
329 // ...
330});
331β
332<form.Field
333 name="age"
334 validatorAdapter={zodValidator}
335 validators={{
336 onChange: z.number().gte(13, "You must be 13 to make an account")
337 }}
338 children={(field) => {
339 return (
340 <>
341 {/* ... */}
342 </>
343 );
344 }}
345/>
346```
347β
348These adapters also support async operations using the proper property names:
349β
350```tsx
351<form.Field
352 name="age"
353 validators={{
354 onChange: z
355 .number()
356 .gte(13, "You must be 13 to make an account"),
357 onChangeAsyncDebounceMs: 500,
358 onChangeAsync: z.number().refine(
359 async (value) => {
360 const currentAge = await fetchCurrentAgeOnProfile();
361 return (
362 value >= currentAge
363 );
364 },
365 {
366 message: "You can only increase the age",
367 },
368 )
369 }}
370 children={(field) => {
371 return (
372 <>
373 {/* ... */}
374 </>
375 );
376 }}
377/>
378```
379β
380## Preventing invalid forms from being submitted
381β
382The `onChange`, `onBlur` etc... callbacks are also run when the form is submitted and the submission is blocked if the form is invalid.
383β
384The 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).
385β
386You can subscribe to it via `form.Subscribe` 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).
387β
388```tsx
389const form = useForm(/* ... */);
390β
391return (
392 /* ... */
393β
394 // Dynamic submit button
395 <form.Subscribe
396 selector={(state) => [state.canSubmit, state.isSubmitting]}
397 children={([canSubmit, isSubmitting]) => (
398 <button type="submit" disabled={!canSubmit}>
399 {isSubmitting ? "..." : "Submit"}
400 </button>
401 )}
402 />
403);
404```