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

dynamic-validation.md

225 lines5.7 KB

1---
2id: dynamic-validation
3title: Dynamic Validation
4---
5​
6In many cases, you want to change the validation rules depending on the state of the form or other conditions. The most popular
7example of this is when you want to validate a field differently based on whether the user has submitted the form for the first time or not.
8​
9We support this through our `onDynamic` validation function.
10​
11```tsx
12import { revalidateLogic, useForm } from '@tanstack/react-form'
13​
14// ...
15​
16const form = useForm({
17 defaultValues: {
18 firstName: '',
19 lastName: '',
20 },
21 // If this is omitted, `onDynamic` will not be called
22 validationLogic: revalidateLogic(),
23 validators: {
24 onDynamic: ({ value }) => {
25 if (!value.firstName) {
26 return { firstName: 'A first name is required' }
27 }
28 return undefined
29 },
30 },
31})
32```
33​
34> [!IMPORTANT]
35> By default, `onDynamic` is not called; therefore you must pass `revalidateLogic()` to the `validationLogic` option of `useForm`.
36​
37## Revalidation Options
38​
39`revalidateLogic` allows you to specify when validation should be run and to change the validation rules dynamically based on the current submission state of the form.
40​
41It takes two arguments:
42​
43- `mode`: The mode of validation prior to the first form submission. This can be one of the following:
44 - `change`: Validate on every change.
45 - `blur`: Validate on blur.
46 - `submit`: Validate on submit. (**default**)
47​
48- `modeAfterSubmission`: The mode of validation after the form has been submitted. This can be one of the following:
49 - `change`: Validate on every change. (**default**)
50 - `blur`: Validate on blur.
51 - `submit`: Validate on submit.
52​
53You can, for example, use the following to revalidate on blur after the first submission:
54​
55```tsx
56const form = useForm({
57 // ...
58 validationLogic: revalidateLogic({
59 mode: 'submit',
60 modeAfterSubmission: 'blur',
61 }),
62 // ...
63})
64```
65​
66## Accessing Errors
67​
68Just as you might access errors from an `onChange` or `onBlur` validation, you can access errors from the `onDynamic` validation function using the `form.state.errorMap` object.
69​
70```tsx
71function App() {
72 const form = useForm({
73 // ...
74 validationLogic: revalidateLogic(),
75 validators: {
76 onDynamic: ({ value }) => {
77 if (!value.firstName) {
78 return { firstName: 'A first name is required' }
79 }
80 return undefined
81 },
82 },
83 })
84​
85 return <p>{form.state.errorMap.onDynamic?.firstName}</p>
87```
88​
89## Usage with Other Validation Logic
90​
91You can use `onDynamic` validation alongside other validation logic, such as `onChange` or `onBlur`.
92​
93```tsx
94import { revalidateLogic, useForm } from '@tanstack/react-form'
95​
96function App() {
97 const form = useForm({
98 defaultValues: {
99 firstName: '',
100 lastName: '',
101 },
102 validationLogic: revalidateLogic(),
103 validators: {
104 onChange: ({ value }) => {
105 if (!value.firstName) {
106 return { firstName: 'A first name is required' }
107 }
108 return undefined
109 },
110 onDynamic: ({ value }) => {
111 if (!value.lastName) {
112 return { lastName: 'A last name is required' }
113 }
114 return undefined
115 },
116 },
117 })
118​
119 return (
120 <div>
121 <p>{form.state.errorMap.onChange?.firstName}</p>
122 <p>{form.state.errorMap.onDynamic?.lastName}</p>
123 </div>
124 )
126```
127​
128### Usage with Fields
129​
130You can also use `onDynamic` validation with fields, just like you would with other validation logic.
131​
132```tsx
133function App() {
134 const form = useForm({
135 defaultValues: {
136 name: '',
137 age: 0,
138 },
139 validationLogic: revalidateLogic(),
140 onSubmit({ value }) {
141 alert(JSON.stringify(value))
142 },
143 })
144​
145 return (
146 <form
147 onSubmit={(e) => {
148 e.preventDefault()
149 e.stopPropagation()
150 form.handleSubmit()
151 }}
152 >
153 <form.Field
154 name={'age'}
155 validators={{
156 onDynamic: ({ value }) =>
157 value > 18 ? undefined : 'Age must be greater than 18',
158 }}
159 children={(field) => (
160 <div>
161 <input
162 type="number"
163 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
164 onBlur={field.handleBlur}
165 value={field.state.value}
166 />
167 <p style={{ color: 'red' }}>
168 {field.state.meta.errorMap.onDynamic}
169 </p>
170 </div>
171 )}
172 />
173 <button type="submit">Submit</button>
174 </form>
175 )
177```
178​
179### Async Validation
180​
181Async validation can also be used with `onDynamicAsync` just like with other validation logic. You can even debounce the async validation to avoid excessive calls.
182​
183```tsx
184const form = useForm({
185 defaultValues: {
186 username: '',
187 },
188 validationLogic: revalidateLogic(),
189 validators: {
190 onDynamicAsyncDebounceMs: 500, // Debounce the async validation by 500ms
191 onDynamicAsync: async ({ value }) => {
192 if (!value.username) {
193 return { username: 'Username is required' }
194 }
195 // Simulate an async validation
196 const isValid = await validateUsername(value.username)
197 return isValid ? undefined : { username: 'Username is already taken' }
198 },
199 },
200})
201```
202​
203### Standard Schema Validation
204​
205You can also use standard schema validation libraries like Valibot or Zod with `onDynamic` validation. This allows you to define complex validation rules that can change dynamically based on the form state.
206​
207```tsx
208import { z } from 'zod'
209​
210const schema = z.object({
211 firstName: z.string().min(1, 'A first name is required'),
212 lastName: z.string().min(1, 'A last name is required'),
213})
214​
215const form = useForm({
216 defaultValues: {
217 firstName: '',
218 lastName: '',
219 },
220 validationLogic: revalidateLogic(),
221 validators: {
222 onDynamic: schema,
223 },
224})
225```