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