TanStackT
TanStack8mo ago
3 replies
sad-indigo

Manually triggering a field validation with form.validateField() not working?

I have a form.FIeld with an onChange validator that depends on a value external to the form. Whenever this external value changes, I want this validator to re-run, so I'm trying to use an effect to manually trigger a validation like so:

useEffect(() => {
  form.validateField('field', 'change')
}, [externalValue])

return (
  <form.Field
    name="field"
    validators={{
      onChange: ({ value }) => {
        if (externalValue < value) return "Error msg"
      }
    }}
    children={() => ...}
   />


There doesn't seem to be any docs explaining how a validator can be manually triggered in response to a non-form value changing, but I saw that this 'validateField' function exists on the form and this seems like it should cause my onChange validator to rerun, but in practice I'm not seeing the onChange callback firing?

For additional context, I'm defining my form like so:

const { fieldContext, formContext } = createFormHookContexts()

const { withForm } = createFormHook({
   fieldContext, formContext, fieldComponents: {}, formComponents: {}
})

const Component = withForm({
  defaultValue: { field: 0 },
  props: { externalValue: 0 }
  render: ({ form, externalValue }) => {
   
    useEffect(() => {
      form.validateField('field', 'change')
    }, [externalValue])

    return (
      <form.Field
        name="field"
        validators={{
          onChange: ({ value }) => {
            if (externalValue < value) return "Error msg"
          }
        }}
        children={() => ...}
     />
  )}
})


tyia
Was this page helpful?