Course contentsShow
← TypeScript
Lesson 1293 of 1,79630. Type-Safe APIsFree lesson

Refinements and Custom Validation

Add custom logic with .refine() to enforce constraints beyond basic type checking, like email format.

Refinements and Custom Validation

What you'll learn: How to add custom validation logic beyond basic type checking using Zod's .refine() method to enforce constraints like email format, age ranges, and business rules.

Going Beyond Type Structure

Zod schemas validate that your data has the correct shape — strings are strings, numbers are numbers, objects have the right properties. But what about rules like "this string must be a valid email" or "this number must be positive"? That's where refinements come in.

Think of refinements as your own custom security checkpoint. The basic schema is like checking someone has a passport; refinements check that the passport isn't expired, the photo matches, and the visa is correct.

Using .refine() for Custom Logic

The .refine() method lets you add a validation function that receives the parsed value and returns true (valid) or false (invalid):

import { z } from 'zod';

const EmailSchema = z.string().refine(
  (value) => value.includes('@'),
  { message: 'Must be a valid email address' }
);

// Valid
EmailSchema.parse('user@example.com'); // ✓

// Invalid - throws error
EmailSchema.parse('notanemail'); // ✗

You can chain multiple refinements to build up complex validation rules:

const PasswordSchema = z.string()
  .min(8)
  .refine((val) => /[A-Z]/.test(val), {
    message: 'Password must contain uppercase letter'
  })
  .refine((val) => /[0-9]/.test(val), {
    message: 'Password must contain a number'
  });

Key Takeaway: Use .refine() to enforce constraints that go beyond type structure — format validation, business rules, cross-field checks — turning Zod schemas into complete validation engines that bridge the gap between TypeScript's compile-time types and runtime data reality.