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

validation.md

563 lines16.1 KB

1---
2id: form-validation
3title: Form and Field Validation
4---
5​
6At the core of TanStack Form's functionality 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, etc.)
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 a 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.isValid && (
37 <em role="alert">{field.state.meta.errors.join(', ')}</em>
38 )}
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.isValid && (
68 <em role="alert">{field.state.meta.errors.join(', ')}</em>
69 )}
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.isValid && (
100 <em role="alert">{field.state.meta.errors.join(', ')}</em>
101 )}
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 information about displaying errors is 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.isValid && (
126 <em>{field.state.meta.errors.join(',')}</em>
127 )}
128 </>
129 )
130 }}
131</form.Field>
132```
133​
134Or use the `errorMap` property to access the specific error you're looking for:
135​
136```tsx
137<form.Field
138 name="age"
139 validators={{
140 onChange: ({ value }) =>
141 value < 13 ? 'You must be 13 to make an account' : undefined,
142 }}
144 {(field) => (
145 <>
146 {/* ... */}
147 {field.state.meta.errorMap['onChange'] ? (
148 <em>{field.state.meta.errorMap['onChange']}</em>
149 ) : null}
150 </>
151 )}
152</form.Field>
153```
154​
155It's worth mentioning that our `errors` array and the `errorMap` match the types returned by the validators. This means that:
156​
157```tsx
158<form.Field
159 name="age"
160 validators={{
161 onChange: ({ value }) => (value < 13 ? { isOldEnough: false } : undefined),
162 }}
164 {(field) => (
165 <>
166 {/* ... */}
167 {/* errorMap.onChange is type `{isOldEnough: false} | undefined` */}
168 {/* meta.errors is type `Array<{isOldEnough: false} | undefined>` */}
169 {!field.state.meta.errorMap['onChange']?.isOldEnough ? (
170 <em>The user is not old enough</em>
171 ) : null}
172 </>
173 )}
174</form.Field>
175```
176​
177## Validation at field-level vs at form-level
178​
179As shown above, each `<Field>` accepts its own validation rules via the callbacks such as `onChange` and `onBlur`. 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.
180​
181Example:
182​
183```tsx
184export default function App() {
185 const form = useForm({
186 defaultValues: {
187 age: 0,
188 },
189 onSubmit: async ({ value }) => {
190 console.log(value)
191 },
192 validators: {
193 // Add validators to the form the same way you would add them to a field
194 onChange({ value }) {
195 if (value.age < 13) {
196 return 'Must be 13 or older to sign'
197 }
198 return undefined
199 },
200 },
201 })
202​
203 // Subscribe to the form's `errorMap` so that updates to it will cause re-renders
204 // Alternatively, you can use `form.Subscribe`
205 const formErrorMap = useStore(form.store, (state) => state.errorMap)
206​
207 return (
208 <div>
209 {/* ... */}
210 {formErrorMap.onChange ? (
211 <div>
212 <em>There was an error on the form: {formErrorMap.onChange}</em>
213 </div>
214 ) : null}
215 {/* ... */}
216 </div>
217 )
219```
220​
221### Setting field-level errors from the form's validators
222​
223You 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.
224​
225```tsx
226export default function App() {
227 const form = useForm({
228 defaultValues: {
229 age: 0,
230 socials: [],
231 details: {
232 email: '',
233 },
234 },
235 validators: {
236 onSubmitAsync: async ({ value }) => {
237 // Validate the value on the server
238 const hasErrors = await verifyDataOnServer(value)
239 if (hasErrors) {
240 return {
241 form: 'Invalid data', // The `form` key is optional
242 fields: {
243 age: 'Must be 13 or older to sign',
244 // Set errors on nested fields with the field's name
245 'socials[0].url': 'The provided URL does not exist',
246 'details.email': 'An email is required',
247 },
248 }
249 }
250​
251 return null
252 },
253 },
254 })
255​
256 return (
257 <div>
258 <form
259 onSubmit={(e) => {
260 e.preventDefault()
261 e.stopPropagation()
262 void form.handleSubmit()
263 }}
264 >
265 <form.Field name="age">
266 {(field) => (
267 <>
268 <label htmlFor={field.name}>Age:</label>
269 <input
270 id={field.name}
271 name={field.name}
272 value={field.state.value}
273 type="number"
274 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
275 />
276 {!field.state.meta.isValid && (
277 <em role="alert">{field.state.meta.errors.join(', ')}</em>
278 )}
279 </>
280 )}
281 </form.Field>
282 <form.Subscribe
283 selector={(state) => [state.errorMap]}
284 children={([errorMap]) =>
285 errorMap.onSubmit ? (
286 <div>
287 <em>There was an error on the form: {errorMap.onSubmit}</em>
288 </div>
289 ) : null
290 }
291 />
292 {/*...*/}
293 </form>
294 </div>
295 )
297```
298​
299> 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.
301> This means that:
303> ```jsx
304> const form = useForm({
305> defaultValues: {
306> age: 0,
307> },
308> validators: {
309> onChange: ({ value }) => {
310> return {
311> fields: {
312> age: value.age < 12 ? 'Too young!' : undefined,
313> },
314> }
315> },
316> },
317> })
319> // ...
321> return (
322> <form.Field
323> name="age"
324> validators={{
325> onChange: ({ value }) => (value % 2 === 0 ? 'Must be odd!' : undefined),
326> }}
327> children={() => <>{/* ... */}</>}
328> />
329> )
330> ```
332> Will only show `'Must be odd!'` even if the 'Too young!' error is returned by the form-level validation.
333​
334## Asynchronous Functional Validation
335​
336While we suspect most validation will be synchronous, there are many instances where a network call or some other async operation would be useful to validate against.
337​
338To do this, we have dedicated `onChangeAsync`, `onBlurAsync`, and other methods that can be used to validate against:
339​
340```tsx
341<form.Field
342 name="age"
343 validators={{
344 onChangeAsync: async ({ value }) => {
345 await new Promise((resolve) => setTimeout(resolve, 1000))
346 return value < 13 ? 'You must be 13 to make an account' : undefined
347 },
348 }}
350 {(field) => (
351 <>
352 <label htmlFor={field.name}>Age:</label>
353 <input
354 id={field.name}
355 name={field.name}
356 value={field.state.value}
357 type="number"
358 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
359 />
360 {!field.state.meta.isValid && (
361 <em role="alert">{field.state.meta.errors.join(', ')}</em>
362 )}
363 </>
364 )}
365</form.Field>
366```
367​
368Synchronous and asynchronous validators can coexist. For example, it is possible to define both `onBlur` and `onBlurAsync` on the same field:
369​
370```tsx
371<form.Field
372 name="age"
373 validators={{
374 onBlur: ({ value }) => (value < 13 ? 'You must be at least 13' : undefined),
375 onBlurAsync: async ({ value }) => {
376 const currentAge = await fetchCurrentAgeOnProfile()
377 return value < currentAge ? 'You can only increase the age' : undefined
378 },
379 }}
381 {(field) => (
382 <>
383 <label htmlFor={field.name}>Age:</label>
384 <input
385 id={field.name}
386 name={field.name}
387 value={field.state.value}
388 type="number"
389 onBlur={field.handleBlur}
390 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
391 />
392 {!field.state.meta.isValid && (
393 <em role="alert">{field.state.meta.errors.join(', ')}</em>
394 )}
395 </>
396 )}
397</form.Field>
398```
399​
400The 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.
401​
402### Built-in Debouncing
403​
404While 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.
405​
406Instead, we enable an easy method for debouncing your `async` calls by adding a single property:
407​
408```tsx
409<form.Field
410 name="age"
411 asyncDebounceMs={500}
412 validators={{
413 onChangeAsync: async ({ value }) => {
414 // ...
415 },
416 }}
417 children={(field) => {
418 return <>{/* ... */}</>
419 }}
420/>
421```
422​
423This will debounce every async call with a 500ms delay. You can even override this property on a per-validation property:
424​
425```tsx
426<form.Field
427 name="age"
428 asyncDebounceMs={500}
429 validators={{
430 onChangeAsyncDebounceMs: 1500,
431 onChangeAsync: async ({ value }) => {
432 // ...
433 },
434 onBlurAsync: async ({ value }) => {
435 // ...
436 },
437 }}
438 children={(field) => {
439 return <>{/* ... */}</>
440 }}
441/>
442```
443​
444This will run `onChangeAsync` every 1500ms, whereas `onBlurAsync` will run every 500ms.
445​
446## Validation through Schema Libraries
447​
448While 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 validators; errors will automatically propagate to the fields.
449​
450### Standard Schema Libraries
451​
452TanStack Form natively supports all libraries following the [Standard Schema specification](https://github.com/standard-schema/standard-schema), most notably:
453​
454- [Zod](https://zod.dev/)
455- [Valibot](https://valibot.dev/)
456- [ArkType](https://arktype.io/)
457- [Effect/Schema](https://effect.website/docs/schema/standard-schema/)
458​
459_Note:_ make sure to use the latest version of the schema libraries as older versions might not support Standard Schema yet.
460​
461> Validation will not provide you with transformed values. See [submission handling](./submission-handling.md) for more information.
462​
463To use schemas from these libraries you can pass them to the `validators` props as you would do with a custom function:
464​
465```tsx
466const userSchema = z.object({
467 age: z.number().gte(13, 'You must be 13 to make an account'),
468})
469​
470function App() {
471 const form = useForm({
472 defaultValues: {
473 age: 0,
474 },
475 validators: {
476 onChange: userSchema,
477 },
478 })
479 return (
480 <div>
481 <form.Field
482 name="age"
483 children={(field) => {
484 return <>{/* ... */}</>
485 }}
486 />
487 </div>
488 )
490```
491​
492Async validators at the form- and field-level are supported as well:
493​
494```tsx
495<form.Field
496 name="age"
497 validators={{
498 onChange: z.number().gte(13, 'You must be 13 to make an account'),
499 onChangeAsyncDebounceMs: 500,
500 onChangeAsync: z.number().refine(
501 async (value) => {
502 const currentAge = await fetchCurrentAgeOnProfile()
503 return value >= currentAge
504 },
505 {
506 message: 'You can only increase the age',
507 },
508 ),
509 }}
510 children={(field) => {
511 return <>{/* ... */}</>
512 }}
513/>
514```
515​
516If you need even more control over your Standard Schema validation, you can combine a Standard Schema with a callback function like so:
517​
518```tsx
519<form.Field
520 name="age"
521 asyncDebounceMs={500}
522 validators={{
523 onChangeAsync: async ({ value, fieldApi }) => {
524 const errors = fieldApi.parseValueWithSchema(
525 z.number().gte(13, 'You must be 13 to make an account'),
526 )
527 if (errors) return errors
528 // continue with your validation
529 },
530 }}
531 children={(field) => {
532 return <>{/* ... */}</>
533 }}
534/>
535```
536​
537## Preventing invalid forms from being submitted
538​
539The callbacks, such as `onChange` and `onBlur`, are also run when the form is submitted and the submission is blocked because the form is invalid.
540​
541The 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).
542​
543You can subscribe to `canSubmit` 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).
544​
545```tsx
546const form = useForm(/* ... */)
547​
548return (
549 /* ... */
550​
551 // Dynamic submit button
552 <form.Subscribe
553 selector={(state) => [state.canSubmit, state.isSubmitting]}
554 children={([canSubmit, isSubmitting]) => (
555 <button type="submit" disabled={!canSubmit}>
556 {isSubmitting ? '...' : 'Submit'}
557 </button>
558 )}
559 />
561```
562​
563To 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.