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

linked-fields.md

75 lines2.2 KB

1---
2id: linked-fields
3title: Link Two Form Fields Together
4---
5​
6You may find yourself needing to link two fields together, such that one is validated when another's value has changed.
7One such use case is when you have both a `password` and a `confirm_password` field.
8Here, you want the `confirm_password` field to error out if its value doesn't match that of the `password` field, regardless of which field triggered the value change.
9​
10Imagine the following user flow:
11​
12- User updates the `confirm_password` field.
13- User updates the `password` field.
14​
15In this example, the form will still have errors present because the `confirm_password` field's validation has not been re-run to mark the field as valid.
16​
17To solve this, you need to make sure that the `confirm_password` field's validation is re-run when the `password` field is updated.
18To do this, you can add an `onChangeListenTo` prop to the `confirm_password` field.
19​
20```tsx
21function App() {
22 const form = useForm({
23 defaultValues: {
24 password: '',
25 confirm_password: '',
26 },
27 // ...
28 })
29​
30 return (
31 <div>
32 <form.Field name="password">
33 {(field) => (
34 <label>
35 <div>Password</div>
36 <input
37 value={field.state.value}
38 onChange={(e) => field.handleChange(e.target.value)}
39 />
40 </label>
41 )}
42 </form.Field>
43 <form.Field
44 name="confirm_password"
45 validators={{
46 onChangeListenTo: ['password'],
47 onChange: ({ value, fieldApi }) => {
48 if (value !== fieldApi.form.getFieldValue('password')) {
49 return 'Passwords do not match'
50 }
51 return undefined
52 },
53 }}
54 >
55 {(field) => (
56 <div>
57 <label>
58 <div>Confirm Password</div>
59 <input
60 value={field.state.value}
61 onChange={(e) => field.handleChange(e.target.value)}
62 />
63 </label>
64 {field.state.meta.errors.map((err) => (
65 <div key={err}>{err}</div>
66 ))}
67 </div>
68 )}
69 </form.Field>
70 </div>
71 )
73```
74​
75This is similar to the `onBlurListenTo` prop, which re-runs the validation when the linked field is blurred.