0
0
NextjsHow-ToBeginner · 4 min read

How to Show Form Errors in Next.js: Simple Guide

In Next.js, you show form errors by using React state to track validation messages and conditionally rendering error text near form fields. Use useState to store errors and update them on form submission or input change, then display errors in your JSX.
📐

Syntax

To show form errors in Next.js, you typically use React's useState to hold error messages. You validate input values on form submission or change, update the error state, and conditionally render error messages in your form.

Key parts:

  • const [errors, setErrors] = useState({}): Holds error messages keyed by field name.
  • handleSubmit: Function to validate inputs and update errors.
  • Conditional rendering: Show error text only if an error exists for a field.
jsx
import { useState } from 'react';

function MyForm() {
  const [errors, setErrors] = useState({});

  function handleSubmit(event) {
    event.preventDefault();
    const form = event.target;
    const newErrors = {};

    if (!form.email.value.includes('@')) {
      newErrors.email = 'Email must include @';
    }

    setErrors(newErrors);

    if (Object.keys(newErrors).length === 0) {
      // proceed with form submission
    }
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <input name="email" type="email" />
      {errors.email && <p role="alert" style={{ color: 'red' }}>{errors.email}</p>}
      <button type="submit">Submit</button>
    </form>
  );
}
Output
A form with an email input and a submit button. If the email is invalid, a red error message appears below the input.
💻

Example

This example shows a simple Next.js form that validates an email and password. Errors appear below each input if validation fails.

jsx
import { useState } from 'react';

export default function SignupForm() {
  const [errors, setErrors] = useState({});
  const [values, setValues] = useState({ email: '', password: '' });

  function handleChange(e) {
    setValues({ ...values, [e.target.name]: e.target.value });
  }

  function handleSubmit(e) {
    e.preventDefault();
    const newErrors = {};

    if (!values.email.includes('@')) {
      newErrors.email = 'Please enter a valid email.';
    }

    if (values.password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters.';
    }

    setErrors(newErrors);

    if (Object.keys(newErrors).length === 0) {
      alert('Form submitted successfully!');
    }
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="email">Email:</label><br />
      <input
        id="email"
        name="email"
        type="email"
        value={values.email}
        onChange={handleChange}
        aria-describedby="email-error"
        aria-invalid={errors.email ? 'true' : 'false'}
      />
      {errors.email && <p id="email-error" role="alert" style={{ color: 'red' }}>{errors.email}</p>}

      <label htmlFor="password">Password:</label><br />
      <input
        id="password"
        name="password"
        type="password"
        value={values.password}
        onChange={handleChange}
        aria-describedby="password-error"
        aria-invalid={errors.password ? 'true' : 'false'}
      />
      {errors.password && <p id="password-error" role="alert" style={{ color: 'red' }}>{errors.password}</p>}

      <button type="submit">Sign Up</button>
    </form>
  );
}
Output
A signup form with email and password fields. If email lacks '@' or password is shorter than 6 characters, red error messages appear below respective inputs.
⚠️

Common Pitfalls

Common mistakes when showing form errors in Next.js include:

  • Not preventing default form submission, causing page reload and losing error state.
  • Not updating error state correctly, so errors don't show or clear properly.
  • Rendering error messages unconditionally, cluttering the UI when no errors exist.
  • Missing accessibility attributes like aria-invalid and role="alert", which help screen readers announce errors.

Always validate inputs before submission and update error state accordingly.

jsx
/* Wrong way: Not preventing default and no error state update */
function WrongForm() {
  function handleSubmit(e) {
    // Missing e.preventDefault()
    alert('Submitted');
  }

  return <form onSubmit={handleSubmit}><button type="submit">Submit</button></form>;
}

/* Right way: Prevent default and update errors */
import { useState } from 'react';
function RightForm() {
  const [errors, setErrors] = useState({});
  function handleSubmit(e) {
    e.preventDefault();
    const newErrors = { field: 'Error message' };
    setErrors(newErrors);
  }
  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
      {errors.field && <p role="alert" style={{ color: 'red' }}>{errors.field}</p>}
    </form>
  );
}
📊

Quick Reference

  • Use useState to store error messages.
  • Validate inputs on submit or change events.
  • Update error state with messages keyed by input name.
  • Render error messages conditionally near inputs.
  • Add aria-invalid and role="alert" for accessibility.
  • Prevent default form submission to control behavior.

Key Takeaways

Use React state with useState to track and display form errors in Next.js.
Validate inputs on submit and update error state to show messages conditionally.
Prevent default form submission to keep control and avoid page reloads.
Add accessibility attributes like aria-invalid and role="alert" for screen reader support.
Clear or update errors properly to keep the UI clean and user-friendly.