Best way to validate related fields? #494
-
Sometimes when validating a field value, we need to access the value of another field. For example a "repeat password" field that needs to be identical to a "password" field. Currently, we could do something like below: <form.Field
name="password"
children={(field) => (
<>
<label htmlFor={field.name}>Password:</label>
<input
name={field.name}
value={field.state.value}
type="password"
onChange={(e) => field.handleChange(e.target.value)}
/>
<FieldInfo field={field} />
</>
)}
/>
<form.Field
name="repeat_password"
onChange={(value, fieldAPI) => {
if (value !== fieldAPI.form.store.state.values.password) {
return "Passwords do not match";
}
}}
children={(field) => (
<>
<label htmlFor={field.name}>Repeat password:</label>
<input
name={field.name}
value={field.state.value}
type="password"
onChange={(e) => field.handleChange(e.target.value)}
/>
<FieldInfo field={field} />
</>
)}
/> But @crutchcorn suggested here that it might not work once we add some performance optimizations in order to limit extra renders for example. Opening this discussion in order to figure out the best way to do this. Once we have an approach, the validation doc will need to be updated. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Thank you for this @juliendelort. I used what you did to achieve similar: <form.Field
name="confirmPassword"
onChange={(value, fieldAPI) => {
if (value !== fieldAPI.form.state.values.password)
return 'Passwords do not match.';
}}
children={(field) => (
<Input
label="Confirm Password"
required
isPassword
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => {
field.handleChange(e.target.value);
}}
errorMsg={field.state.meta.errors.join('\n')}
/>
)}
/> It works great...for now.
|
Beta Was this translation helpful? Give feedback.
-
There's now an official API to do this: https://tanstack.com/form/latest/docs/framework/react/guides/linked-fields |
Beta Was this translation helpful? Give feedback.
There's now an official API to do this:
https://tanstack.com/form/latest/docs/framework/react/guides/linked-fields