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 `<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 }}
25>
26 {(field) => (
27 <>
28 <label for={field().name}>Age:</label>
29 <input
30 id={field().name}
31 name={field().name}
32 value={field().state.value}
33 type="number"
34 onInput={(e) => field().handleChange(e.target.valueAsNumber)}
35 />
36 {!field().state.meta.isValid ? (
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 onChange: ({ value }) =>
51 value < 13 ? 'You must be 13 to make an account' : undefined,
52 }}
53>
54 {(field) => (
55 <>
56 <label for={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 onInput, so that TanStack Form receives the changes
65 onInput={(e) => field().handleChange(e.target.valueAsNumber)}
66 />
67 {!field().state.meta.isValid ? (
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 }}
85>
86 {(field) => (
87 <>
88 <label for={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 onInput, so that TanStack Form receives the changes
97 onInput={(e) => field().handleChange(e.target.valueAsNumber)}
98 />
99 {!field().state.meta.isValid ? (
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 }}
120>
121 {(field) => {
122 return (
123 <>
124 {/* ... */}
125 {!field().state.meta.isValid ? (
126 <em>{field().state.meta.errors.join(',')}</em>
127 ) : null}
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 }}
143>
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` matches 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 }}
163>
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 `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 `createForm()` hook.
180β
181Example:
182β
183```tsx
184export default function App() {
185 const form = createForm(() => ({
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 error map so that updates to it will render
204 // alternately, you can use `form.Subscribe`
205 const formErrorMap = form.useStore((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 )
218}
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
226import { Show } from 'solid-js'
227import { createForm } from '@tanstack/solid-form'
228β
229export default function App() {
230 const form = createForm(() => ({
231 defaultValues: {
232 age: 0,
233 socials: [],
234 details: {
235 email: '',
236 },
237 },
238 validators: {
239 onSubmitAsync: async ({ value }) => {
240 // Validate the value on the server
241 const hasErrors = await validateDataOnServer(value)
242 if (hasErrors) {
243 return {
244 form: 'Invalid data', // The `form` key is optional
245 fields: {
246 age: 'Must be 13 or older to sign',
247 // Set errors on nested fields with the field's name
248 'socials[0].url': 'The provided URL does not exist',
249 'details.email': 'An email is required',
250 },
251 }
252 }
253β
254 return null
255 },
256 },
257 }))
258β
259 return (
260 <div>
261 <form
262 onSubmit={(e) => {
263 e.preventDefault()
264 e.stopPropagation()
265 void form.handleSubmit()
266 }}
267 >
268 <form.Field
269 name="age"
270 children={(field) => (
271 <>
272 <label for={field().name}>Age:</label>
273 <input
274 id={field().name}
275 name={field().name}
276 value={field().state.value}
277 type="number"
278 onChange={(e) => field().handleChange(e.target.valueAsNumber)}
279 />
280 <Show when={field().state.meta.errors.length > 0}>
281 <em role="alert">{field().state.meta.errors.join(', ')}</em>
282 </Show>
283 </>
284 )}
285 />
286 <form.Subscribe
287 selector={(state) => ({ errors: state.errors })}
288 children={(state) => (
289 <Show when={state().errors.length > 0}>
290 <div>
291 <em>
292 There was an error on the form: {state().errors.join(', ')}
293 </em>
294 </div>
295 </Show>
296 )}
297 />
298β
299 <button type="submit">Submit</button>
300 {/*...*/}
301 </form>
302 </div>
303 )
304}
305```
306β
307> 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.
308>
309> This means that:
310>
311> ```tsx
312> const form = createForm(() => ({
313> defaultValues: {
314> age: 0,
315> },
316> validators: {
317> onChange: ({ value }) => {
318> return {
319> fields: {
320> age: value.age < 12 ? 'Too young!' : undefined,
321> },
322> };
323> },
324> },
325> }));
326>
327> return (
328> <form.Field
329> name="age"
330> validators={{
331> onChange: ({ value }) => (value % 2 === 0 ? 'Must be odd!' : undefined),
332> }}
333> children={() => <>{/* ... */}</>}
334> />
335> );
336> }
337> ```
338>
339> Will only show `'Must be odd!` even if the 'Too young!' error is returned by the form-level validation.
340β
341## Asynchronous Functional Validation
342β
343While 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.
344β
345To do this, we have dedicated `onChangeAsync`, `onBlurAsync`, and other methods that can be used to validate against:
346β
347```tsx
348<form.Field
349 name="age"
350 validators={{
351 onChangeAsync: async ({ value }) => {
352 await new Promise((resolve) => setTimeout(resolve, 1000))
353 return value < 13 ? 'You must be 13 to make an account' : undefined
354 },
355 }}
356>
357 {(field) => (
358 <>
359 <label for={field().name}>Age:</label>
360 <input
361 id={field().name}
362 name={field().name}
363 value={field().state.value}
364 type="number"
365 onInput={(e) => field().handleChange(e.target.valueAsNumber)}
366 />
367 {!field().state.meta.isValid ? (
368 <em role="alert">{field().state.meta.errors.join(', ')}</em>
369 ) : null}
370 </>
371 )}
372</form.Field>
373```
374β
375Synchronous and Asynchronous validations can coexist. For example, it is possible to define both `onBlur` and `onBlurAsync` on the same field:
376β
377```tsx
378<form.Field
379 name="age"
380 validators={{
381 onBlur: ({ value }) => (value < 13 ? 'You must be at least 13' : undefined),
382 onBlurAsync: async ({ value }) => {
383 const currentAge = await fetchCurrentAgeOnProfile()
384 return value < currentAge ? 'You can only increase the age' : undefined
385 },
386 }}
387>
388 {(field) => (
389 <>
390 <label for={field().name}>Age:</label>
391 <input
392 id={field().name}
393 name={field().name}
394 value={field().state.value}
395 type="number"
396 onBlur={field().handleBlur}
397 onInput={(e) => field().handleChange(e.target.valueAsNumber)}
398 />
399 {field().state.meta.errors ? (
400 <em role="alert">{field().state.meta.errors.join(', ')}</em>
401 ) : null}
402 </>
403 )}
404</form.Field>
405```
406β
407The 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.
408β
409### Built-in Debouncing
410β
411While 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.
412β
413Instead, we enable an easy method for debouncing your `async` calls by adding a single property:
414β
415```tsx
416<form.Field
417 name="age"
418 asyncDebounceMs={500}
419 validators={{
420 onChangeAsync: async ({ value }) => {
421 // ...
422 },
423 }}
424 children={(field) => {
425 return <>{/* ... */}</>
426 }}
427/>
428```
429β
430This will debounce every async call with a 500ms delay. You can even override this property on a per-validation property:
431β
432```tsx
433<form.Field
434 name="age"
435 asyncDebounceMs={500}
436 validators={{
437 onChangeAsyncDebounceMs: 1500,
438 onChangeAsync: async ({ value }) => {
439 // ...
440 },
441 onBlurAsync: async ({ value }) => {
442 // ...
443 },
444 }}
445 children={(field) => {
446 return <>{/* ... */}</>
447 }}
448/>
449```
450β
451This will run `onChangeAsync` every 1500ms while `onBlurAsync` will run every 500ms.
452β
453## Validation through Schema Libraries
454β
455While 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.
456β
457### Standard Schema Libraries
458β
459TanStack Form natively supports all libraries following the [Standard Schema specification](https://github.com/standard-schema/standard-schema), most notably:
460β
461- [Zod](https://zod.dev/)
462- [Valibot](https://valibot.dev/)
463- [ArkType](https://arktype.io/)
464β
465_Note:_ make sure to use the latest version of the schema libraries as older versions might not support Standard Schema yet.
466β
467> Validation will not provide you with transformed values. See [submission handling](./submission-handling.md) for more information.
468β
469To use schemas from these libraries you can pass them to the `validators` props as you would do with a custom function:
470β
471```tsx
472import { z } from 'zod'
473β
474// ...
475β
476const form = createForm(() => ({
477 // ...
478}))
479β
480;<form.Field
481 name="age"
482 validators={{
483 onChange: z.number().gte(13, 'You must be 13 to make an account'),
484 }}
485 children={(field) => {
486 return <>{/* ... */}</>
487 }}
488/>
489```
490β
491Async validations on form and field level are supported as well:
492β
493```tsx
494<form.Field
495 name="age"
496 validators={{
497 onChange: z.number().gte(13, 'You must be 13 to make an account'),
498 onChangeAsyncDebounceMs: 500,
499 onChangeAsync: z.number().refine(
500 async (value) => {
501 const currentAge = await fetchCurrentAgeOnProfile()
502 return value >= currentAge
503 },
504 {
505 message: 'You can only increase the age',
506 },
507 ),
508 }}
509 children={(field) => {
510 return <>{/* ... */}</>
511 }}
512/>
513```
514β
515If you need even more control over your Standard Schema validation, you can combine a Standard Schema with a callback function like so:
516β
517```tsx
518<form.Field
519 name="age"
520 validators={{
521 onChange: ({ value, fieldApi }) => {
522 const errors = fieldApi.parseValueWithSchema(
523 z.number().gte(13, 'You must be 13 to make an account'),
524 )
525β
526 if (errors) return errors
527β
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 `onChange`, `onBlur` etc... callbacks are also run when the form is submitted and the submission is blocked if 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 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).
544β
545```tsx
546const form = createForm(() => ({
547 /* ... */
548}))
549β
550return (
551 /* ... */
552β
553 // Dynamic submit button
554 <form.Subscribe
555 selector={(state) => ({
556 canSubmit: state.canSubmit,
557 isSubmitting: state.isSubmitting,
558 })}
559 children={(state) => (
560 <button type="submit" disabled={!state().canSubmit}>
561 {state().isSubmitting ? '...' : 'Submit'}
562 </button>
563 )}
564 />
565)
566```
567β
568To 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.