Skip to content

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

@alikhani-dev

Description

@alikhani-dev

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions