React-hook-form: Trigger field validation through all field array items

Viewed 327

I have a field array like this:

const { append, remove, fields } = useFieldArray<CampaignFormValues, 'assortmentNeeds'>({
  name: 'assortmentNeeds',
})

And assortmentNeeds has the following values:

export interface AssortmentNeeds {
  campaignId: string
  productGroup?: string
  category?: string
  demand?: number
  demandRatio?: number
}

Now when one demandRatio value changes, I want to trigger the validation for all demandRatios of all items of the field array.

So, ideally I'd like to have something like this in a hook:

const { trigger, control } = useFormContext<CampaignFormValues>()

const assortmentNeeds = useWatch<CampaignFormValues, `assortmentNeeds.${number}`>({
  name: `assortmentNeeds.${index}` as const,
  control,
}) as AssortmentNeeds

useEffect(() => {
  trigger('assortmentNeeds.0...10.demandRatio')
}, [trigger, assortmentNeeds.demandRatio])

But of course 0...10 is not a valid index. How can I trigger the demandRatio field of all field items?

0 Answers
Related