T
TanStack•4mo ago
rare-sapphire

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={() => ...}
/>
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={() => ...}
/>
)}
})
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
3 Replies
equal-aqua
equal-aqua•4mo ago
That looks like it should work. Could you create a stackblitz reproduction of this not working? validateField simply expects a FieldApi to be present, which is the case since you return one in your Component.
rare-sapphire
rare-sapphireOP•4mo ago
Just tried this with form.AppField and it works as expected 🤔
equal-aqua
equal-aqua•4mo ago
AppField is just a wrapper for Field, so that shouldn‘t be the deciding factor

Did you find this page helpful?