0
0
NextjsHow-ToBeginner · 3 min read

How to Validate Form in Next.js: Simple Guide with Example

In Next.js, you can validate forms by using React's useState to track input values and errors, and handle validation inside the onSubmit event. You check input values against rules, update error states, and prevent form submission if validation fails.
📐

Syntax

To validate a form in Next.js, use React hooks to manage form state and errors. The key parts are:

  • useState to store input values and error messages.
  • onChange handlers to update input values as the user types.
  • onSubmit handler to check inputs against validation rules.
  • Conditional rendering to show error messages.
javascript
const [formData, setFormData] = useState({ field: '' });
const [errors, setErrors] = useState({});

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

function validate() {
  const newErrors = {};
  if (!formData.field.trim()) newErrors.field = 'Field is required';
  return newErrors;
}

function handleSubmit(e) {
  e.preventDefault();
  const validationErrors = validate();
  if (Object.keys(validationErrors).length === 0) {
    // submit form
  } else {
    setErrors(validationErrors);
  }
}
💻

Example

This example shows a simple Next.js form with validation for a name field. It prevents submission if the name is empty and shows an error message.

javascript
import { useState } from 'react';

export default function ContactForm() {
  const [formData, setFormData] = useState({ name: '' });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

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

  function validate() {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = 'Name is required';
    }
    return newErrors;
  }

  function handleSubmit(e) {
    e.preventDefault();
    const validationErrors = validate();
    if (Object.keys(validationErrors).length === 0) {
      setErrors({});
      setSubmitted(true);
    } else {
      setErrors(validationErrors);
      setSubmitted(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="name">Name:</label><br />
      <input
        type="text"
        id="name"
        name="name"
        value={formData.name}
        onChange={handleChange}
        aria-describedby="name-error"
        aria-invalid={errors.name ? 'true' : 'false'}
      /><br />
      {errors.name && <span id="name-error" style={{ color: 'red' }}>{errors.name}</span>}<br />
      <button type="submit">Submit</button>
      {submitted && <p style={{ color: 'green' }}>Form submitted successfully!</p>}
    </form>
  );
}
Output
A form with a text input labeled 'Name'. If submitted empty, a red error message 'Name is required' appears below the input. If filled and submitted, a green success message 'Form submitted successfully!' appears.
⚠️

Common Pitfalls

Common mistakes when validating forms in Next.js include:

  • Not preventing the default form submission with e.preventDefault(), causing page reload.
  • Not trimming input values before validation, which can allow spaces to pass as valid input.
  • Not updating error state properly, so errors don't show or clear correctly.
  • Missing accessibility attributes like aria-invalid and aria-describedby for screen readers.
javascript
/* Wrong way: No preventDefault, no trimming, no error state update */
function handleSubmit(e) {
  // Missing e.preventDefault()
  if (!formData.name) {
    alert('Name required');
  }
}

/* Right way: */
function handleSubmit(e) {
  e.preventDefault();
  if (!formData.name.trim()) {
    setErrors({ name: 'Name is required' });
  } else {
    setErrors({});
    // proceed
  }
}
📊

Quick Reference

Tips for validating forms in Next.js:

  • Use useState to track inputs and errors.
  • Always call e.preventDefault() in onSubmit.
  • Trim input values before checking if empty.
  • Show error messages conditionally below inputs.
  • Add accessibility attributes for better user experience.

Key Takeaways

Use React hooks like useState to manage form data and errors in Next.js.
Always prevent default form submission to control validation flow.
Trim input values before validating to avoid false positives.
Show clear error messages and use accessibility attributes for better UX.
Validate inputs inside the onSubmit handler before processing form data.