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()` method accepts some callbacks as validators 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```ts
19import { html, nothing } from 'lit'
20;`${this.#form.field(
21 {
22 name: 'age',
23 validators: {
24 onChange: ({ value }) =>
25 value < 13 ? 'You must be 13 to make an account' : undefined,
26 },
27 },
28 (field) => {
29 return html`
30 <label for="${field.name}">Age:</label>
31 <input
32 id="${field.name}"
33 name="${field.name}"
34 .value="${field.state.value}"
35 type="number"
36 @input="${(e: Event) => {
37 const target = e.target as HTMLInputElement
38 field.handleChange(target.valueAsNumber)
39 }}"
40 />
41 ${!field.state.meta.isValid
42 ? html`<em role="alert">${field.state.meta.errors.join(', ')}</em>`
43 : nothing}
44 `
45 },
46)}`
47```
48β
49In 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:
50β
51```ts
52import { html, nothing } from 'lit'
53;`${this.#form.field(
54 {
55 name: 'age',
56 validators: {
57 onBlur: ({ value }) =>
58 value < 13 ? 'You must be 13 to make an account' : undefined,
59 },
60 },
61 (field) => {
62 return html`
63 <label for="${field.name}">Age:</label>
64 <input
65 id="${field.name}"
66 name="${field.name}"
67 .value="${field.state.value}"
68 type="number"
69 @blur="${() => field.handleBlur()}"
70 @input="${(e: Event) => {
71 const target = e.target as HTMLInputElement
72 field.handleChange(target.valueAsNumber)
73 }}"
74 />
75 ${!field.state.meta.isValid
76 ? html`<em role="alert">${field.state.meta.errors.join(', ')}</em>`
77 : nothing}
78 `
79 },
80)}`
81```
82β
83So you can control when the validation is done by implementing the desired callback. You can even perform different pieces of validation at different times:
84β
85```ts
86import { html, nothing } from 'lit'
87;`${this.#form.field(
88 {
89 name: 'age',
90 validators: {
91 onChange: ({ value }) =>
92 value < 13 ? 'You must be 13 to make an account' : undefined,
93 onBlur: ({ value }) => (value < 0 ? 'Invalid value' : undefined),
94 },
95 },
96 (field) => {
97 return html`
98 <label for="${field.name}">Age:</label>
99 <input
100 id="${field.name}"
101 name="${field.name}"
102 .value="${field.state.value}"
103 type="number"
104 @blur="${() => field.handleBlur()}"
105 @input="${(e: Event) => {
106 const target = e.target as HTMLInputElement
107 field.handleChange(target.valueAsNumber)
108 }}"
109 />
110 ${!field.state.meta.isValid
111 ? html`<em role="alert">${field.state.meta.errors.join(', ')}</em>`
112 : nothing}
113 `
114 },
115)}`
116```
117β
118In 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.
119β
120## Displaying Errors
121β
122Once you have your validation in place, you can map the errors from an array to be displayed in your UI:
123β
124```ts
125import { html, nothing } from 'lit'
126;`${this.#form.field(
127 {
128 name: 'age',
129 validators: {
130 onChange: ({ value }) =>
131 value < 13 ? 'You must be 13 to make an account' : undefined,
132 },
133 },
134 (field) => {
135 return html`
136 <!-- ... -->
137 ${!field.state.meta.isValid
138 ? html`<em>${field.state.meta.errors.join(',')}</em>`
139 : nothing}
140 `
141 },
142)}`
143```
144β
145Or use the `errorMap` property to access the specific error you're looking for:
146β
147```ts
148import { html, nothing } from 'lit'
149;`${this.#form.field(
150 {
151 name: 'age',
152 validators: {
153 onChange: ({ value }) =>
154 value < 13 ? 'You must be 13 to make an account' : undefined,
155 },
156 },
157 (field) => {
158 return html`
159 <!-- ... -->
160 ${field.state.meta.errorMap['onChange']
161 ? html`<em>${field.state.meta.errorMap['onChange']}</em>`
162 : nothing}
163 `
164 },
165)}`
166```
167β
168It's worth mentioning that our `errors` array and the `errorMap` matches the types returned by the validators. This means that:
169β
170```ts
171import { html, nothing } from 'lit'
172β
173;`${this.#form.field(
174 {
175 name: 'age',
176 validators: {
177 onChange: ({ value }) => (value < 13 ? { isOldEnough: false } : undefined),
178 },
179 },
180 (field) => {
181 return html`
182 <!-- ... -->
183 <!-- errorMap.onChange is type `{isOldEnough: false} | undefined` -->
184 <!-- meta.errors is type `Array<{isOldEnough: false} | undefined>` -->
185 ${!field.state.meta.errorMap['onChange']?.isOldEnough
186 ? html`<em>The user is not old enough</em>`
187 : nothing}
188 `
189 },
190)}`
191```
192β
193## Validation at field level vs at form level
194β
195As 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 `TanStackFormController` constructor.
196β
197Example:
198β
199```ts
200import { LitElement, html, nothing } from 'lit'
201import { customElement } from 'lit/decorators.js'
202import { TanStackFormController } from '@tanstack/lit-form'
203β
204@customElement('my-form')
205export class MyForm extends LitElement {
206 #form = new TanStackFormController(this, {
207 defaultValues: {
208 age: 0,
209 },
210 onSubmit: async ({ value }) => {
211 console.log(value)
212 },
213 validators: {
214 // Add validators to the form the same way you would add them to a field
215 onChange({ value }) {
216 if (value.age < 13) {
217 return 'Must be 13 or older to sign'
218 }
219 return undefined
220 },
221 },
222 })
223β
224 render() {
225 return html`
226 <div>
227 <!-- ... -->
228 ${this.#form.api.state.errorMap.onChange
229 ? html`
230 <div>
231 <em
232 >There was an error on the form:
233 ${this.#form.api.state.errorMap.onChange}</em
234 >
235 </div>
236 `
237 : nothing}
238 <!-- ... -->
239 </div>
240 `
241 }
242}
243```
244β
245### Setting field-level errors from the form's validators
246β
247You 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.
248β
249```ts
250import { LitElement, html, nothing } from 'lit'
251import { customElement } from 'lit/decorators.js'
252import { TanStackFormController } from '@tanstack/lit-form'
253β
254@customElement('my-form')
255export class MyForm extends LitElement {
256 #form = new TanStackFormController(this, {
257 defaultValues: {
258 age: 0,
259 socials: [],
260 details: {
261 email: '',
262 },
263 },
264 validators: {
265 onSubmitAsync: async ({ value }) => {
266 // Validate the value on the server
267 const hasErrors = await verifyDataOnServer(value)
268 if (hasErrors) {
269 return {
270 form: 'Invalid data', // The `form` key is optional
271 fields: {
272 age: 'Must be 13 or older to sign',
273 // Set errors on nested fields with the field's name
274 'socials[0].url': 'The provided URL does not exist',
275 'details.email': 'An email is required',
276 },
277 }
278 }
279β
280 return null
281 },
282 },
283 })
284β
285 render() {
286 return html`
287 <div>
288 <form
289 @submit="${(e: Event) => {
290 e.preventDefault()
291 e.stopPropagation()
292 this.#form.api.handleSubmit()
293 }}"
294 >
295 ${this.#form.field(
296 { name: 'age' },
297 (field) => html`
298 <label for="${field.name}">Age:</label>
299 <input
300 id="${field.name}"
301 name="${field.name}"
302 .value="${field.state.value}"
303 type="number"
304 @input="${(e: Event) => {
305 const target = e.target as HTMLInputElement
306 field.handleChange(target.valueAsNumber)
307 }}"
308 />
309 ${!field.state.meta.isValid
310 ? html`<em role="alert"
311 >${field.state.meta.errors.join(', ')}</em
312 >`
313 : nothing}
314 `,
315 )}
316 ${this.#form.api.state.errorMap.onSubmit
317 ? html`
318 <div>
319 <em
320 >There was an error on the form:
321 ${this.#form.api.state.errorMap.onSubmit}</em
322 >
323 </div>
324 `
325 : nothing}
326 <!--...-->
327 </form>
328 </div>
329 `
330 }
331}
332```
333β
334> 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.
335>
336> This means that:
337>
338> ```ts
339> const form = new TanStackFormController(this, {
340> defaultValues: {
341> age: 0,
342> },
343> validators: {
344> onChange: ({ value }) => {
345> return {
346> fields: {
347> age: value.age < 12 ? 'Too young!' : undefined,
348> },
349> }
350> },
351> },
352> })
353>
354> // ...
355>
356> return html`
357> ${this.#form.field(
358> {
359> name: 'age',
360> validators: {
361> onChange: ({ value }) =>
362> value % 2 === 0 ? 'Must be odd!' : undefined,
363> },
364> },
365> () => html`<!-- ... -->`,
366> )}
367> `
368> ```
369>
370> Will only show `'Must be odd!` even if the 'Too young!' error is returned by the form-level validation.
371β
372## Asynchronous Functional Validation
373β
374While 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.
375β
376To do this, we have dedicated `onChangeAsync`, `onBlurAsync`, and other methods that can be used to validate against:
377β
378```ts
379import { html, nothing } from 'lit'
380;`${this.#form.field(
381 {
382 name: 'age',
383 validators: {
384 onChangeAsync: async ({ value }) => {
385 await new Promise((resolve) => setTimeout(resolve, 1000))
386 return value < 13 ? 'You must be 13 to make an account' : undefined
387 },
388 },
389 },
390 (field) => {
391 return html`
392 <label for="${field.name}">Age:</label>
393 <input
394 id="${field.name}"
395 name="${field.name}"
396 .value="${field.state.value}"
397 type="number"
398 @input="${(e: Event) => {
399 const target = e.target as HTMLInputElement
400 field.handleChange(target.valueAsNumber)
401 }}"
402 />
403 ${!field.state.meta.isValid
404 ? html`<em role="alert">${field.state.meta.errors.join(', ')}</em>`
405 : nothing}
406 `
407 },
408)}`
409```
410β
411Synchronous and Asynchronous validations can coexist. For example, it is possible to define both `onBlur` and `onBlurAsync` on the same field:
412β
413```ts
414import { html, nothing } from 'lit'
415;`${this.#form.field(
416 {
417 name: 'age',
418 validators: {
419 onBlur: ({ value }) =>
420 value < 13 ? 'You must be at least 13' : undefined,
421 onBlurAsync: async ({ value }) => {
422 const currentAge = await fetchCurrentAgeOnProfile()
423 return value < currentAge ? 'You can only increase the age' : undefined
424 },
425 },
426 },
427 (field) => {
428 return html`
429 <label for="${field.name}">Age:</label>
430 <input
431 id="${field.name}"
432 name="${field.name}"
433 .value="${field.state.value}"
434 type="number"
435 @blur="${() => field.handleBlur()}"
436 @input="${(e: Event) => {
437 const target = e.target as HTMLInputElement
438 field.handleChange(target.valueAsNumber)
439 }}"
440 />
441 ${!field.state.meta.isValid
442 ? html`<em role="alert">${field.state.meta.errors.join(', ')}</em>`
443 : nothing}
444 `
445 },
446)}`
447```
448β
449The 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.
450β
451### Built-in Debouncing
452β
453While 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.
454β
455Instead, we enable an easy method for debouncing your `async` calls by adding a single property:
456β
457```ts
458;`${this.#form.field(
459 {
460 name: 'age',
461 asyncDebounceMs: 500,
462 validators: {
463 onChangeAsync: async ({ value }) => {
464 // ...
465 },
466 },
467 },
468 (field) => {
469 return html`<!-- ... -->`
470 },
471)}`
472```
473β
474This will debounce every async call with a 500ms delay. You can even override this property on a per-validation property:
475β
476```ts
477;`${this.#form.field(
478 {
479 name: 'age',
480 asyncDebounceMs: 500,
481 validators: {
482 onChangeAsyncDebounceMs: 1500,
483 onChangeAsync: async ({ value }) => {
484 // ...
485 },
486 onBlurAsync: async ({ value }) => {
487 // ...
488 },
489 },
490 },
491 (field) => {
492 return html`<!-- ... -->`
493 },
494)}`
495```
496β
497This will run `onChangeAsync` every 1500ms while `onBlurAsync` will run every 500ms.
498β
499## Validation through Schema Libraries
500β
501While 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.
502β
503### Standard Schema Libraries
504β
505TanStack Form natively supports all libraries following the [Standard Schema specification](https://github.com/standard-schema/standard-schema), most notably:
506β
507- [Zod](https://zod.dev/)
508- [Valibot](https://valibot.dev/)
509- [ArkType](https://arktype.io/)
510- [Effect/Schema](https://effect.website/docs/schema/standard-schema/)
511β
512_Note:_ make sure to use the latest version of the schema libraries as older versions might not support Standard Schema yet.
513β
514> Validation will not provide you with transformed values. Use submission handling (docs pending).
515β
516To use schemas from these libraries you can pass them to the `validators` props as you would do with a custom function:
517β
518```ts
519import { z } from 'zod'
520import { LitElement, html } from 'lit'
521import { customElement } from 'lit/decorators.js'
522import { TanStackFormController } from '@tanstack/lit-form'
523β
524const userSchema = z.object({
525 age: z.number().gte(13, 'You must be 13 to make an account'),
526})
527β
528@customElement('my-form')
529export class MyForm extends LitElement {
530 #form = new TanStackFormController(this, {
531 defaultValues: {
532 age: 0,
533 },
534 validators: {
535 onChange: userSchema,
536 },
537 })
538β
539 render() {
540 return html`
541 <div>
542 ${this.#form.field({ name: 'age' }, (field) => {
543 return html`<!-- ... -->`
544 })}
545 </div>
546 `
547 }
548}
549```
550β
551Async validations on form and field level are supported as well:
552β
553```ts
554import { html } from 'lit'
555import { z } from 'zod'
556β
557${this.#form.field(
558 {
559 name: 'age',
560 validators: {
561 onChange: z.number().gte(13, 'You must be 13 to make an account'),
562 onChangeAsyncDebounceMs: 500,
563 onChangeAsync: z.number().refine(
564 async (value) => {
565 const currentAge = await fetchCurrentAgeOnProfile()
566 return value >= currentAge
567 },
568 {
569 message: 'You can only increase the age',
570 },
571 ),
572 },
573 },
574 (field) => {
575 return html`<!-- ... -->`
576 },
577)}
578```
579β
580If you need even more control over your Standard Schema validation, you can combine a Standard Schema with a callback function like so:
581β
582```ts
583import { html } from 'lit'
584import { z } from 'zod'
585β
586${this.#form.field(
587 {
588 name: 'age',
589 asyncDebounceMs: 500,
590 validators: {
591 onChangeAsync: async ({ value, fieldApi }) => {
592 const errors = fieldApi.parseValueWithSchema(
593 z.number().gte(13, 'You must be 13 to make an account'),
594 )
595 if (errors) return errors
596 // continue with your validation
597 },
598 },
599 },
600 (field) => {
601 return html`<!-- ... -->`
602 },
603)}
604```
605β
606## Preventing invalid forms from being submitted
607β
608The `onChange`, `onBlur` etc... callbacks are also run when the form is submitted and the submission is blocked if the form is invalid.
609β
610The 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).
611β
612You can access this flag via `this.#form.api.state` 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).
613β
614```ts
615class MyForm extends LitElement {
616 #form = new TanStackFormController(this, {
617 /* ... */
618 })
619β
620 render() {
621 return html`
622 <!-- ... -->
623β
624 <!-- Dynamic submit button -->
625 <button type="submit" ?disabled="${!this.#form.api.state.canSubmit}">
626 ${this.#form.api.state.isSubmitting ? '...' : 'Submit'}
627 </button>
628 `
629 }
630}
631```
632β
633To 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.