Form Validation in Next.js

In this tutorial, you will learn about Form Validations in Next.js. We have two types of validations.

  1. Client-side validations.
  2. Server-side validations.

1. Client Side validation

Client-side validation means the Form will validate on the browser side, not the server side.

Example: In the example below, you will see email validation on the client side.


"use client";
import { useState } from "react";

export default function LoginForm() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!email.includes("@")) {
      setError("Enter a valid email address");
      return;
    }

    alert("Form submitted!");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <p style={{ color: "red" }}>{error}</p>
      <button>Submit</button>
    </form>
  );
}

2. Server-side validation

Server-side validation means the Form will validate on the server side, not the client side.

Example:


"use server";

export async function register(formData) {
  const email = formData.get("email");

  if (!email.includes("@")) {
    return { error: "Invalid email" };
  }

  // proceed with DB
}

Form Validation in Next.js – Interview Questions

Q 1: What types of form validation exist?
Ans: Client-side and server-side validation.
Q 2: Which is more secure?
Ans: Server-side validation.
Q 3: Can libraries be used?
Ans: Yes, Zod and Yup are common.
Q 4: Can validation be done in Server Actions?
Ans: Yes.
Q 5: Why is validation important?
Ans: Data integrity and security.

Form Validation in Next.js – Objective Questions (MCQs)

Q1. Client-side form validation is commonly done using:






Q2. Which attribute enables basic HTML validation?






Q3. Server-side validation helps to:






Q4. Which library is commonly used for form validation in Next.js?






Q5. Where should sensitive validation always occur?






Related Form Validation in Next.js Topics