Validation Schemas
This page provides detailed documentation for all available Zod validation schemas in the AI-Enhanced TypeScript Template.
AppConfigSchema
Validates the structure of application configuration files, typically config.json
.
Schema Definition
typescript
export const AppConfigSchema = z.object({
app: z.object({
name: z.string().min(1, 'App name cannot be empty'),
version: z.string().regex(/^\d+\.\d+\.\d+$/, 'Version must follow semver format'),
environment: z.enum(['development', 'production', 'test'])
}),
server: z.object({
port: z.number().int().min(1).max(65535),
host: z.string().min(1, 'Host cannot be empty'),
timeout: z.number().int().min(1000).max(300000)
}),
logging: z.object({
level: z.enum(['error', 'warn', 'info', 'debug']),
outputFile: z.string().nullable(),
includeTimestamp: z.boolean(),
useColors: z.boolean()
}),
features: z.object({
enableMetrics: z.boolean(),
enableHealthCheck: z.boolean(),
enableCors: z.boolean()
})
});
Usage Example
typescript
import { validateAppConfig } from './validation.js';
// Valid configuration
const config = {
app: {
name: 'my-app',
version: '1.0.0',
environment: 'development'
},
server: {
port: 3000,
host: 'localhost',
timeout: 30000
},
logging: {
level: 'info',
outputFile: null,
includeTimestamp: true,
useColors: true
},
features: {
enableMetrics: false,
enableHealthCheck: true,
enableCors: true
}
};
const result = validateAppConfig(config);
if (result.success) {
// TypeScript knows the exact type
console.log(`Starting ${result.data.app.name} v${result.data.app.version}`);
console.log(`Server will run on ${result.data.server.host}:${result.data.server.port}`);
}
Validation Rules
Field | Type | Rules | Description |
---|---|---|---|
app.name | string | min(1) | Application name, cannot be empty |
app.version | string | semver regex | Must follow semantic versioning (x.y.z) |
app.environment | enum | development/production/test | Runtime environment |
server.port | number | 1-65535 | Valid port number |
server.host | string | min(1) | Server hostname or IP |
server.timeout | number | 1000-300000ms | Request timeout in milliseconds |
logging.level | enum | error/warn/info/debug | Log level |
logging.outputFile | string|null | - | Optional log file path |
features.* | boolean | - | Feature flags |
UserInputSchema
Validates user input data for APIs, forms, and user-generated content.
Schema Definition
typescript
export const UserInputSchema = z.object({
name: z.string().min(1, 'Name is required').max(100, 'Name cannot exceed 100 characters'),
email: z.string().email('Invalid email format'),
age: z.number().int().min(0, 'Age cannot be negative').max(150, 'Age cannot exceed 150').optional(),
preferences: z.object({
theme: z.enum(['light', 'dark', 'auto']).default('auto'),
notifications: z.boolean().default(true),
language: z.string().length(2, 'Language code must be 2 characters').default('en')
}).optional()
});
Usage Example
typescript
import { validateUserInput } from './validation.js';
// API endpoint example
app.post('/api/users', (req, res) => {
const userResult = validateUserInput(req.body);
if (!userResult.success) {
return res.status(400).json({
error: 'Validation failed',
details: userResult.error
});
}
// Use validated data
const user = userResult.data;
console.log(`Creating user: ${user.name} (${user.email})`);
// Save user to database...
res.json({ success: true, user });
});
Validation Rules
Field | Type | Rules | Description |
---|---|---|---|
name | string | min(1), max(100) | User's full name |
email | string | email format | Valid email address |
age | number? | 0-150, optional | User's age (optional) |
preferences.theme | enum? | light/dark/auto | UI theme preference |
preferences.notifications | boolean? | default: true | Notification settings |
preferences.language | string? | 2 chars, default: 'en' | Language code |
ServerConfigSchema
Validates server configuration with intelligent defaults for production deployment.
Schema Definition
typescript
export const ServerConfigSchema = z.object({
port: z.number().int().min(1).max(65535),
host: z.string().ip().or(z.literal('localhost')),
timeout: z.number().int().positive(),
maxConnections: z.number().int().positive().default(100),
enableSsl: z.boolean().default(false),
sslOptions: z.object({
keyPath: z.string().min(1),
certPath: z.string().min(1)
}).optional()
});
Usage Example
typescript
import { validateServerConfig } from './validation.js';
// Server startup
const serverOptions = {
port: process.env.PORT ? parseInt(process.env.PORT) : 3000,
host: process.env.HOST || 'localhost',
timeout: 30000,
enableSsl: process.env.NODE_ENV === 'production'
};
const result = validateServerConfig(serverOptions);
if (result.success) {
const config = result.data;
const server = createServer(config);
server.listen(config.port, config.host, () => {
console.log(`Server running on ${config.host}:${config.port}`);
console.log(`Max connections: ${config.maxConnections}`);
console.log(`SSL enabled: ${config.enableSsl}`);
});
} else {
console.error('Invalid server configuration:', result.error);
process.exit(1);
}
Validation Rules
Field | Type | Rules | Description |
---|---|---|---|
port | number | 1-65535 | Server port number |
host | string | IP or 'localhost' | Server hostname |
timeout | number | positive | Request timeout in ms |
maxConnections | number | positive, default: 100 | Max concurrent connections |
enableSsl | boolean | default: false | Enable HTTPS |
sslOptions.keyPath | string? | min(1) | SSL private key path |
sslOptions.certPath | string? | min(1) | SSL certificate path |
Type Inference
All schemas automatically generate TypeScript types:
typescript
import type { AppConfig, UserInput, ServerConfig } from './validation.js';
// These types are automatically inferred from the schemas
type AppConfig = z.infer<typeof AppConfigSchema>;
type UserInput = z.infer<typeof UserInputSchema>;
type ServerConfig = z.infer<typeof ServerConfigSchema>;
// Use in function signatures
function startServer(config: ServerConfig): void {
// TypeScript knows all the properties and their types
}
function createUser(input: UserInput): Promise<User> {
// Full type safety with validated input
}
Schema Composition
Schemas can be composed and extended:
typescript
// Extend UserInputSchema for admin users
const AdminUserSchema = UserInputSchema.extend({
role: z.enum(['admin', 'moderator']),
permissions: z.array(z.string())
});
// Partial schemas for updates
const UserUpdateSchema = UserInputSchema.partial();
// Pick specific fields
const UserEmailSchema = UserInputSchema.pick({ email: true });