T
TanStack2w ago
quickest-silver

Revalidate array field on array items update

I have an array field with a validator:
<form.Field
name="commissionPayablePercentages"
mode="array"
validators={{
onChange: ({ value }) => {
const total = value.reduce(
(sum, item) => sum + Number(item.percentage || 0),
0
)
return total !== 100 ? ['Total must be 100%'] : []
},
}}
>
<form.Field
name="commissionPayablePercentages"
mode="array"
validators={{
onChange: ({ value }) => {
const total = value.reduce(
(sum, item) => sum + Number(item.percentage || 0),
0
)
return total !== 100 ? ['Total must be 100%'] : []
},
}}
>
Each item has a percentage field:
<form.Field name={`commissionPayablePercentages[${i}].percentage`}>
{(f) => (
<NumberField
value={f.state.value}
onChange={f.handleChange}
/>
)}
</form.Field>
<form.Field name={`commissionPayablePercentages[${i}].percentage`}>
{(f) => (
<NumberField
value={f.state.value}
onChange={f.handleChange}
/>
)}
</form.Field>
Issue: validation only triggers when adding a new array item. Need: run validation 500ms after typing in any percentage field (debounce).
10 Replies
equal-aqua
equal-aqua2w ago
That sounds like a bug. Do you have a reproducible example? On Stackblitz, for example?
quickest-silver
quickest-silverOP2w ago
Here : https://vitejsvitekbgnqrsm-ip1w--5173--cf284e50.local-credentialless.webcontainer.io/ In this example I do not have a debounce so the validation errors whould be shown as soon as I type a value right ?
quickest-silver
quickest-silverOP2w ago
equal-aqua
equal-aqua2w ago
I see ... yeah, feels strange. The main cause is that the array doesn't trigger call its validator when child properties update. pushValue explicitly calls it, for example
quickest-silver
quickest-silverOP2w ago
Okay, any workarounds for this?
equal-aqua
equal-aqua2w ago
a form validator that sets the field level error should work for this I see you got a schema on change, but that can still be kept:
validators: {
onChange: ({ formApi, value }) => {
const schemaErrors = formApi.parseValuesWithSchema(schema)
if (schemaErrors) return schemaErrors;

// validate it sums to 100
if (sum !== 100) {
return { fields: { commissionPayablePercentages: "Total must be 100%" } }
}
}
}
validators: {
onChange: ({ formApi, value }) => {
const schemaErrors = formApi.parseValuesWithSchema(schema)
if (schemaErrors) return schemaErrors;

// validate it sums to 100
if (sum !== 100) {
return { fields: { commissionPayablePercentages: "Total must be 100%" } }
}
}
}
quickest-silver
quickest-silverOP2w ago
Okay and this can be debounced too right?
equal-aqua
equal-aqua2w ago
hmm ... the schema would also be debounced as far as I know. Though you seem to use revalidateLogic anyways, so I'm not sure a schema is needed for any non-onDynamic validation
quickest-silver
quickest-silverOP2w ago
Sorry, but I am a but confused if you meant this would work or not?
equal-aqua
equal-aqua2w ago
yes, it would work

Did you find this page helpful?