CodingNic

Authentication & Sessions

Validate Registration Input

Authentication & Sessions 12 min read

Validate Registration Input

Validate Registration Input

Task

Add a Zod schema for registration so invalid credentials are rejected before they reach Prisma.

File

Create or update:

text
lib/validation/auth.ts

Implementation

ts
import { z } from "zod";

export const registerSchema = z.object({
  name: z.string().trim().min(2).max(80),
  email: z.string().trim().email().transform((value) => value.toLowerCase()),
  password: z.string().min(8).max(128),
});

Use the schema at the registration boundary:

ts
const parsed = registerSchema.safeParse(await request.json());

if (!parsed.success) {
  return Response.json({ error: "Invalid registration data" }, { status: 400 });
}

const { name, email, password } = parsed.data;

Keep validation close to the server boundary. Client-side validation can improve the form experience, but the server must remain authoritative.

Test

Submit:

  • a valid name, email, and password
  • an invalid email
  • a password shorter than 8 characters

The server should reject invalid input with a 400 response.

Checkpoint

Registration input is validated before any user record is created.