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

custom-errors.md

277 lines6.7 KB

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
48 field.state.meta.errors.map((error, i) => (
49 <div key={i} className="error">
50 {error}
51 </div>
52 ))
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
95 field.state.meta.errors[0] === true && (
96 <div className="error">You must accept the terms</div>
97 )
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
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 )
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
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 )
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
194 field.state.meta.errorMap.onChange && (
195 <div className="real-time-error">{field.state.meta.errorMap.onChange}</div>
196 )
198​
200 field.state.meta.errorMap.onBlur && (
201 <div className="blur-feedback">{field.state.meta.errorMap.onBlur}</div>
202 )
204​
206 field.state.meta.errorMap.onSubmit && (
207 <div className="submit-error">{field.state.meta.errorMap.onSubmit}</div>
208 )
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.