Overview
What is Schema Validation?
Schema validation allows you to automatically generate validation rules and types from your database table definitions. Instead of manually writing validation code for inserts, updates, and data queries, you can generate schemas directly using popular validation libraries.
Supported validation libraries: Zod, Valibot, TypeBox, ArkType.
Note
Schema generation works for both database tables and views, automatically respecting column constraints such as nullability, default values, and generated columns.
Generating Schemas
Understanding Schema Generation Functions
To generate a validation schema, import the relevant creation functions for your chosen validation library. There are three main schema generation functions available:
createSelectSchema: Generates a schema for validating records fetched from the database (all fields are present, nullable columns allow nulls).createInsertSchema: Generates a schema for validating new records before insertion (fields with defaults or auto-incrementing values become optional).createUpdateSchema: Generates a schema for updating records (all fields become optional).
Code Example
import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';
import { createSelectSchema, createInsertSchema, createUpdateSchema } from 'drizzle-zod';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email'),
});
// Generate validation schemas
export const selectUserSchema = createSelectSchema(users);
export const insertUserSchema = createInsertSchema(users);
export const updateUserSchema = createUpdateSchema(users);Customizing and Refining Schemas
Adding Custom Field Rules
You can refine individual fields when generating schemas by passing a second argument containing your custom rules.
import { z } from 'zod';
const insertUserSchema = createInsertSchema(users, {
email: (schema) => schema.email().email(), // Add email format validation
name: z.string().min(2), // Override the name schema entirely
});Advanced Configuration Options
Enabling Type Coercion (Zod)
When using Zod, you can use a schema factory to enable automatic type coercion for primitive values like numbers, booleans, dates, strings, and bigints.
Supported coercion types: bigint, boolean, date, number, string.
import { createSchemaFactory } from 'drizzle-zod';
const { createInsertSchema } = createSchemaFactory({
coerce: {
number: true,
boolean: true,
},
});
export const insertSchema = createInsertSchema(users);Tip
Setting coerce: true enables type coercion for all supported primitive types simultaneously.