TanStackT
TanStack10mo ago
11 replies
skinny-azure

Conditionally rendered fields validation

Is there a better way to check validation for conditionally rendered fields?


Here is an example of what I have got working:
const otherField = useStore(form.store, state => state.values.otherField)

{otherField && (
  <form.Field
    name="field"
    validators={{
      onSubmit: (value) => {
        if (!form.state.values.otherField) {
          return undefined;
        }

        // isNonNegativeFloat = some ZodNumber validation
        const result = isNonNegativeFloat('field').safeParse(value.value);

        if (result.success) {
          return undefined;
        }

        return result.error.errors[0].message;
      },
    }}
  />
)}


This works but it's quite complicated, especially if you consider multiple layers of nesting e.g.
if (!form.store.state.values.otherField || form.store.state.values.otherFieldFalsy) {
  return undefined;
}
Was this page helpful?