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

validation.md

401 lines11.5 KB

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