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

linked-fields.md

74 lines2.2 KB

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