Open History to see the last commit
1---
2id: custom-errors
3title: Custom Errors
4---
5β
6TanStack Form provides complete flexibility in the types of error values you can return from validators. String errors are the most common and easy to work with, but the library allows you to return any type of value from your validators.
7β
8As a general rule, any truthy value is considered an error and will mark the form or field as invalid, while falsy values (`false`, `undefined`, `null`, etc.) mean there is no error, and the form or field is valid.
9β
10## Return String Values from Forms
11β
12```tsx
13<form.Field
14 name="username"
15 validators={{
16 onChange: ({ value }) =>
17 value.length < 3 ? 'Username must be at least 3 characters' : undefined,
18 }}
19/>
20```
21β
22For form-level validation affecting multiple fields:
23β
24```tsx
25const form = useForm({
26 defaultValues: {
27 username: '',
28 email: '',
29 },
30 validators: {
31 onChange: ({ value }) => {
32 return {
33 fields: {
34 username:
35 value.username.length < 3 ? 'Username too short' : undefined,
36 email: !value.email.includes('@') ? 'Invalid email' : undefined,
37 },
38 }
39 },
40 },
41})
42```
43β
44String errors are the most common type and are easily displayed in your UI:
45β
46```tsx
47{
48 field.state.meta.errors.map((error, i) => (
49 <div key={i} className="error">
50 {error}
51 </div>
52 ))
53}
54```
55β
56### Numbers
57β
58Useful for representing quantities, thresholds, or magnitudes:
59β
60```tsx
61<form.Field
62 name="age"
63 validators={{
64 onChange: ({ value }) => (value < 18 ? 18 - value : undefined),
65 }}
66/>
67```
68β
69Display in UI:
70β
71```tsx
72// TypeScript knows the error is a number based on your validator
73<div className="error">
74 You need {field.state.meta.errors[0]} more years to be eligible
75</div>
76```
77β
78### Booleans
79β
80Simple flags to indicate error state:
81β
82```tsx
83<form.Field
84 name="accepted"
85 validators={{
86 onChange: ({ value }) => (!value ? true : undefined),
87 }}
88/>
89```
90β
91Display in UI:
92β
93```tsx
94{
95 field.state.meta.errors[0] === true && (
96 <div className="error">You must accept the terms</div>
97 )
98}
99```
100β
101### Objects
102β
103Rich error objects with multiple properties:
104β
105```tsx
106<form.Field
107 name="email"
108 validators={{
109 onChange: ({ value }) => {
110 if (!value.includes('@')) {
111 return {
112 message: 'Invalid email format',
113 severity: 'error',
114 code: 1001,
115 }
116 }
117 return undefined
118 },
119 }}
120/>
121```
122β
123Display in UI:
124β
125```tsx
126{
127 typeof field.state.meta.errors[0] === 'object' && (
128 <div className={`error ${field.state.meta.errors[0].severity}`}>
129 {field.state.meta.errors[0].message}
130 <small> (Code: {field.state.meta.errors[0].code})</small>
131 </div>
132 )
133}
134```
135β
136In the example above, the rendered message, code and styling depend on the event error you want to display.
137β
138### Arrays
139β
140Multiple error messages for a single field:
141β
142```tsx
143<form.Field
144 name="password"
145 validators={{
146 onChange: ({ value }) => {
147 const errors = []
148 if (value.length < 8) errors.push('Password too short')
149 if (!/[A-Z]/.test(value)) errors.push('Missing uppercase letter')
150 if (!/[0-9]/.test(value)) errors.push('Missing number')
151β
152 return errors.length ? errors : undefined
153 },
154 }}
155/>
156```
157β
158Display in UI:
159β
160```tsx
161{
162 Array.isArray(field.state.meta.errors) && (
163 <ul className="error-list">
164 {field.state.meta.errors.map((err, i) => (
165 <li key={i}>{err}</li>
166 ))}
167 </ul>
168 )
169}
170```
171β
172## The `disableErrorFlat` Prop on Fields
173β
174By default, TanStack Form flattens errors from all validation sources (`onChange`, `onBlur`, `onSubmit`) into a single `errors` array. The `disableErrorFlat` prop preserves the error sources:
175β
176```tsx
177<form.Field
178 name="email"
179 disableErrorFlat
180 validators={{
181 onChange: ({ value }) =>
182 !value.includes('@') ? 'Invalid email format' : undefined,
183 onBlur: ({ value }) =>
184 !value.endsWith('.com') ? 'Only .com domains allowed' : undefined,
185 onSubmit: ({ value }) => (value.length < 5 ? 'Email too short' : undefined),
186 }}
187/>
188```
189β
190Without `disableErrorFlat`, all errors would be combined into `field.state.meta.errors`. With it, you can access errors by their source:
191β
192```tsx
193{
194 field.state.meta.errorMap.onChange && (
195 <div className="real-time-error">{field.state.meta.errorMap.onChange}</div>
196 )
197}
198β
199{
200 field.state.meta.errorMap.onBlur && (
201 <div className="blur-feedback">{field.state.meta.errorMap.onBlur}</div>
202 )
203}
204β
205{
206 field.state.meta.errorMap.onSubmit && (
207 <div className="submit-error">{field.state.meta.errorMap.onSubmit}</div>
208 )
209}
210```
211β
212This is useful for:
213β
214- Displaying different types of errors with different UI treatments
215- Prioritizing errors (e.g., showing submission errors more prominently)
216- Implementing progressive disclosure of errors
217β
218## Type Safety of `errors` and `errorMap`
219β
220TanStack Form provides strong type safety for error handling. Each key in the `errorMap` has exactly the type returned by its corresponding validator, while the `errors` array contains a union type of all the possible error values from all validators:
221β
222```tsx
223<form.Field
224 name="password"
225 validators={{
226 onChange: ({ value }) => {
227 // This returns a string or undefined
228 return value.length < 8 ? 'Too short' : undefined
229 },
230 onBlur: ({ value }) => {
231 // This returns an object or undefined
232 if (!/[A-Z]/.test(value)) {
233 return { message: 'Missing uppercase', level: 'warning' }
234 }
235 return undefined
236 },
237 }}
238 children={(field) => {
239 // TypeScript knows that errors[0] can be string | { message: string, level: string } | undefined
240 const error = field.state.meta.errors[0]
241β
242 // Type-safe error handling
243 if (typeof error === 'string') {
244 return <div className="string-error">{error}</div>
245 } else if (error && typeof error === 'object') {
246 return <div className={error.level}>{error.message}</div>
247 }
248β
249 return null
250 }}
251/>
252```
253β
254The `errorMap` property is also fully typed, matching the return types of your validation functions:
255β
256```tsx
257// With disableErrorFlat
258<form.Field
259 name="email"
260 disableErrorFlat
261 validators={{
262 onChange: ({ value }): string | undefined =>
263 !value.includes("@") ? "Invalid email" : undefined,
264 onBlur: ({ value }): { code: number, message: string } | undefined =>
265 !value.endsWith(".com") ? { code: 100, message: "Wrong domain" } : undefined
266 }}
267 children={(field) => {
268 // TypeScript knows the exact type of each error source
269 const onChangeError: string | undefined = field.state.meta.errorMap.onChange;
270 const onBlurError: { code: number, message: string } | undefined = field.state.meta.errorMap.onBlur;
271β
272 return (/* ... */);
273 }}
274/>
275```
276β
277This type safety helps catch errors at compile time instead of runtime, making your code more reliable and maintainable.