Create User Validation Schema

Create src/validators/user.validator.js.

We will define a schema for user registration.

Zod provides methods such as:

  • string().
  • email().
  • min().
  • max().
  • number().
  • int().
  • optional().
  • object().
  • strict().

The strict method rejects unexpected object properties, helping prevent unwanted fields from being passed through.

Password Length

bcrypt has a 72-byte input limit. For password hashing, enforce a byte-aware maximum or use an appropriate pre-hashing strategy rather than relying only on JavaScript character counts.

src/validators/user.validator.js
import { z } from 'zod';

export const createUserSchema = z.object({
  name: z.string().trim().min(2).max(80),
  email: z.string().trim().email().max(254),
  password: z.string().min(8).max(72),
  age: z.number().int().min(18).max(120).optional()
}).strict();

export const updateUserSchema = z.object({
  name: z.string().trim().min(2).max(80).optional(),
  email: z.string().trim().email().max(254).optional(),
  age: z.number().int().min(18).max(120).optional()
}).strict().refine(
  (data) => Object.keys(data).length > 0,
  { message: 'At least one field must be provided' }
);

Defines strict registration and partial-update schemas. Password is accepted during registration, but deliberately excluded from the general update schema.

Key Takeaways
  • Zod provides reusable validation schemas.

  • strict() rejects unexpected properties.

  • Separate registration and update validation.