#Revalidate array field on array items update

12 messages · Page 1 of 1 (latest)

hallow saddle
#

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%'] : []
    },
  }}
>

Each item has a percentage 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).

inland jetty
#

That sounds like a bug. Do you have a reproducible example? On Stackblitz, for example?

hallow saddle
#

In this example I do not have a debounce so the validation errors whould be shown as soon as I type a value right ?

inland jetty
hallow saddle
#

Okay, any workarounds for this?

inland jetty
#

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%" } }
     }
  }
}
hallow saddle
#

Okay and this can be debounced too right?

inland jetty
#

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

hallow saddle
#

Sorry, but I am a but confused if you meant this would work or not?