Validation Overview
The AI-Enhanced TypeScript Template includes a comprehensive validation system built on Zod, providing runtime type safety and detailed error reporting for your TypeScript applications.
What is Zod Validation?
Zod is a TypeScript-first schema validation library that allows you to:
- Define schemas that describe the shape of your data
- Validate data at runtime with detailed error messages
- Infer TypeScript types automatically from your schemas
- Compose complex validations from simple building blocks
Key Features
🛡️ Type Safety
- Runtime validation ensures data matches TypeScript types
- Automatic type inference from Zod schemas
- Compile-time safety with full TypeScript integration
📝 Detailed Error Messages
- Field-level validation with specific error descriptions
- Custom error messages for better user experience
- Structured error reporting with ValidationError class
🔧 Easy Integration
- Drop-in replacement for manual validation code
- Composable schemas for complex data structures
- Framework agnostic - works with any TypeScript project
Available Schemas
The template includes three pre-built validation schemas:
AppConfigSchema
Validates application configuration files (config.json):
typescript
import { validateAppConfig } from './validation.js';
const result = validateAppConfig(configData);
if (result.success) {
// Use validated config
console.log(result.data.app.name);
} else {
// Handle validation errors
console.error(result.error);
}
UserInputSchema
Validates user input for APIs and forms:
typescript
import { validateUserInput } from './validation.js';
const userResult = validateUserInput(requestBody);
if (!userResult.success) {
return res.status(400).json({ error: userResult.error });
}
// Use validated user data
ServerConfigSchema
Validates server configuration with intelligent defaults:
typescript
import { validateServerConfig } from './validation.js';
const serverResult = validateServerConfig(serverOptions);
if (serverResult.success) {
// Start server with validated config
server.listen(serverResult.data.port);
}
Quick Start
1. Import Validation Functions
typescript
import {
validateAppConfig,
validateUserInput,
validateServerConfig
} from './validation.js';
2. Validate Your Data
typescript
const result = validateUserInput({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
if (result.success) {
// Data is valid and typed
const user = result.data; // TypeScript knows the exact type
} else {
// Handle validation error
console.error('Validation failed:', result.error);
}
3. Handle Validation Results
All validation functions return a Result
type:
typescript
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
Error Handling
The validation system includes a custom ValidationError
class that provides:
- Formatted error messages with field-level details
- Issue tracking for multiple validation failures
- Structured error information for API responses
typescript
import { ValidationError } from './validation.js';
try {
const data = AppConfigSchema.parse(input);
} catch (error) {
if (error instanceof ValidationError) {
console.log(error.getFormattedMessage());
// Access individual issues
error.issues.forEach(issue => {
console.log(`${issue.path.join('.')}: ${issue.message}`);
});
}
}
Best Practices
✅ Do
- Validate all external data (API requests, config files, user input)
- Use specific schemas for different data types
- Handle validation errors gracefully with user-friendly messages
- Leverage TypeScript inference from Zod schemas
❌ Don't
- Skip validation for "trusted" data sources
- Use
any
types when Zod can provide specific types - Ignore validation errors - always handle them appropriately
- Create overly complex schemas - keep them focused and composable
Next Steps
- Learn about specific schemas →
- See practical usage examples →
- Understand error handling →
- Create custom schemas →