# ErrorMessage

> Render validation error messages for a registered field. Supports multiple errors per field and custom message rendering in React Hook Form.

Source: https://react-hook-form.com/docs/useformstate/errormessage

## `ErrorMessage:` `Component` _(since v7.88.0)_

A simple component to render associated input's error message. Reads from the `control` prop when supplied, otherwise from the nearest [`FormProvider`](https://react-hook-form.com/docs/formprovider).

### Props

---

| Name      | Type                                                                              | Required | Description                                                                                                                                                                                          |
| --------- | --------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`    | `string`                                                       | ✓        | Name of the field, or a global error path (`root` or `root.*`).                                                                                                                                      |
| `control` | [Control](https://react-hook-form.com/ts#Control)                                       |          | `control` object provided by `useForm`. Optional if you are using `FormProvider`.                                                                                                                    |
| `as`      | `React.ElementType`                                            |          | Wrapper component or HTML tag. For example: `as="span"` or `as={Text}`                                                                                                                               |
| `render`  | `({ message: string, messages?: Object}) => React.ReactNode` |          | This is a [render prop](https://legacy.reactjs.org/docs/render-props.html) for rendering error message or messages.<br/><br/>**Note:** you need to set `criteriaMode` to 'all' for using `messages`. |

### Examples

---

**Single Error Message**

**TS**

[Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-errormessage-d1ues)

```tsx
import { useForm, ErrorMessage } from "react-hook-form"

interface FormInputs {
  singleErrorInput: string
}

export default function App() {
  const { register, control, handleSubmit } = useForm<FormInputs>()
  const onSubmit = (data: FormInputs) => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("singleErrorInput", { required: "This is required." })}
      />
      <ErrorMessage control={control} name="singleErrorInput" />

      <ErrorMessage
        control={control}
        name="singleErrorInput"
        render={({ message }) => <p>{message}</p>}
      />

      <input type="submit" />
    </form>
  )
}
```

**JS**

[Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-errormessage-jufsl)

```javascript
import { useForm, ErrorMessage } from "react-hook-form"

export default function App() {
  const { register, control, handleSubmit } = useForm()
  const onSubmit = (data) => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("singleErrorInput", { required: "This is required." })}
      />
      <ErrorMessage control={control} name="singleErrorInput" />

      <ErrorMessage
        control={control}
        name="singleErrorInput"
        render={({ message }) => <p>{message}</p>}
      />

      <input type="submit" />
    </form>
  )
}
```

**Multiple Error Messages**

**TS**

[Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v6-ts-errormessage-multiple-error-messages-forked-sy5f0)

```tsx
import { useForm, ErrorMessage } from "react-hook-form"

interface FormInputs {
  multipleErrorInput: string
}

export default function App() {
  const { register, control, handleSubmit } = useForm<FormInputs>({
    criteriaMode: "all",
  })
  const onSubmit = (data: FormInputs) => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("multipleErrorInput", {
          required: "This is required.",
          pattern: {
            value: /\d+/,
            message: "This input is number only.",
          },
          maxLength: {
            value: 10,
            message: "This input exceed maxLength.",
          },
        })}
      />
      <ErrorMessage
        control={control}
        name="multipleErrorInput"
        render={({ messages }) =>
          messages &&
          Object.entries(messages).map(([type, message]) => (
            <p key={type}>{message}</p>
          ))
        }
      />

      <input type="submit" />
    </form>
  )
}
```

**JS**

[Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-errormessage-multiple-error-messages-lnvkt)

```javascript
import { useForm, ErrorMessage } from "react-hook-form"

export default function App() {
  const { register, control, handleSubmit } = useForm({
    criteriaMode: "all",
  })
  const onSubmit = (data) => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("multipleErrorInput", {
          required: "This is required.",
          pattern: {
            value: /\d+/,
            message: "This input is number only.",
          },
          maxLength: {
            value: 10,
            message: "This input exceed maxLength.",
          },
        })}
      />
      <ErrorMessage
        control={control}
        name="multipleErrorInput"
        render={({ messages }) =>
          messages &&
          Object.entries(messages).map(([type, message]) => (
            <p key={type}>{message}</p>
          ))
        }
      />

      <input type="submit" />
    </form>
  )
}
```

**With `FormProvider`**

```tsx
import { useForm, FormProvider, ErrorMessage } from "react-hook-form"

function Field() {
  return <ErrorMessage name="singleErrorInput" />
}

export default function App() {
  const methods = useForm()

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit((data) => console.log(data))}>
        <input
          {...methods.register("singleErrorInput", {
            required: "This is required.",
          })}
        />
        <Field />

        <input type="submit" />
      </form>
    </FormProvider>
  )
}
```

### Tips

---

- `as` only wraps the message text and does not receive other props. To add a class name, an `id` for `aria-describedby`, or `role="alert"`, use `render`:

  ```javascript
  <ErrorMessage
    name="email"
    render={({ message }) => (
      <p id="email-error" role="alert" className="field-error">
        {message}
      </p>
    )}
  />
  ```

- Each `ErrorMessage` subscribes only to the errors for its `name`, so you can use many of them without re-rendering the whole form.
- Use `name="root.server"` to show the error set by the [`Form`](https://react-hook-form.com/docs/useform/form) component, or any root error you set with [`setError`](https://react-hook-form.com/docs/useform/seterror).
