error-message icon indicating copy to clipboard operation
error-message copied to clipboard

ErrorMessage` does not show `useFieldArray` array-level errors stored on `errors[name].root

Open alikhani-dev opened this issue 5 months ago • 0 comments

When using useFieldArray with rules, React Hook Form places array-level validation errors under a non-index root property of the errors array. @hookform/error-message does not display these when using name="spec".

Code:

import { useForm, useFieldArray } from "react-hook-form";
import { ErrorMessage } from "@hookform/error-message";

type FormValues = { spec: { value: string }[] };

export default function Demo() {
  const { control, register, handleSubmit, formState: { errors } } =
    useForm<FormValues>({ defaultValues: { spec: [] } });

  const { fields } = useFieldArray({
    control,
    name: "spec",
    rules: {
      required: "At least one item is required",
      minLength: { value: 3, message: "At least 3 items" },
      maxLength: { value: 5, message: "At most 5 items" },
    },
  });

  return (
    <form onSubmit={handleSubmit(() => {})}>
      {fields.map((f, i) => (
        <input
          key={f.id}
          {...register(`spec.${i}.value`, { required: "Required" })}
        />
      ))}

      {/* Does not render array-level errors */}
      <ErrorMessage errors={errors} name="spec" />

      {/* Workaround that works */}
      <ErrorMessage errors={errors} name="spec.root" />
    </form>
  );
}

Actual error shape (simplified):

errors = {
  spec: [
    /* per-index errors (often undefined) */,
    root: {
      type: "required",
      message: "At least one item is required",
      ref: { name: "spec" },
    },
  ],
};

Expected behavior: <ErrorMessage name="spec" /> should also display errors.spec.root.message when present.

Minimal reproduction: https://codesandbox.io/p/sandbox/2zlgzn

Workaround: Use name="spec.root" for array-level errors.

alikhani-dev avatar Sep 06 '25 08:09 alikhani-dev