Course contentsShow
← React
Lesson 1220 of 2,39631. Forms in ReactFree lesson

Displaying Errors with formState.errors

Accessing validation errors from formState to show field-specific error messages to users.

Displaying Errors with formState.errors

You'll learn how to show field-specific validation error messages to users by accessing React Hook Form's error state.

The Core Idea

After you've registered inputs with validation rules, React Hook Form tracks which fields have errors and what those errors are. The formState.errors object is a mirror of your form structure, containing error objects only for fields that failed validation. Each error object has a message property you can display.

Think of formState.errors like a report card that only shows the failed subjects—if a field passes validation, it simply won't appear in the errors object.

Accessing and Displaying Errors

After calling useForm(), destructure formState from the returned object, then access its errors property:

const { register, handleSubmit, formState } = useForm();
const { errors } = formState;

Now you can conditionally render error messages for specific fields:

<input 
  {...register("email", { 
    required: "Email is required",
    pattern: {
      value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
      message: "Invalid email address"
    }
  })} 
/>
{errors.email && <span>{errors.email.message}</span>}

The pattern is simple: check if errors.fieldName exists, and if so, display errors.fieldName.message. This only shows errors for fields that have actually failed validation.

Multiple Fields

Each field gets its own error entry:

{errors.username && <p>{errors.username.message}</p>}
{errors.password && <p>{errors.password.message}</p>}

Key Takeaway: formState.errors provides a structured object matching your form shape, where each failed field contains a message property you can conditionally render to guide users toward fixing validation problems.