Zod - TypeScript Schema Validation

Zod - TypeScript Schema Validation



Zod is a TypeScript-first schema validation library with static type inference, designed to validate data at runtime with full TypeScript support.

GitHub


https://github.com/colinhacks/zod

What is Zod?



Zod allows you to:
  • Define schemas for your data
  • Validate data at runtime
  • Automatically infer TypeScript types
  • Transform data during validation


  • Key Features



    1. TypeScript-First

  • Full type inference
  • No separate type definitions
  • Zero configuration


  • 2. Runtime Validation

  • Validate API responses
  • Check form data
  • Sanitize user input


  • 3. Composable

  • Combine schemas easily
  • Reuse validation logic
  • Modular design


  • Basic Usage



    Define a Schema



    text
    ypescript
    import { z } from 'zod'
    
    // Simple schema
    const UserSchema = z.object({
      name: z.string(),
      age: z.number(),
      email: z.string().email(),
    })
    
    // Infer TypeScript type
    type User = z.infer<typeof UserSchema>
    // { name: string, age: number, email: string }
    


    Validate Data



    text
    ypescript
    // Validate and parse
    try {
      const user = UserSchema.parse({
        name: 'John',
        age: 30,
        email: 'john@example.com',
      })
      console.log(user)
    } catch (error) {
      console.error('Validation failed:', error)
    }
    
    // Safe parse (doesn't throw)
    const result = UserSchema.safeParse({
      name: 'John',
      age: 'invalid',
    })
    
    if (result.success) {
      console.log(result.data)
    } else {
      console.log(result.error)
    }
    


    Advanced Validation



    text
    ypescript
    const UserSchema = z.object({
      name: z.string().min(2).max(100),
      age: z.number().min(18).max(120),
      email: z.string().email(),
      website: z.string().url().optional(),
      role: z.enum(['admin', 'user', 'guest']),
      tags: z.array(z.string()),
      metadata: z.record(z.any()),
      active: z.boolean().default(true),
      createdAt: z.date().default(() => new Date()),
    })
    


    Custom Validation



    text
    ypescript
    const PasswordSchema = z.string()
      .min(8, 'Password must be at least 8 characters')
      .regex(/[A-Z]/, 'Must contain uppercase letter')
      .regex(/[0-9]/, 'Must contain number')
      .regex(/[^a-zA-Z0-9]/, 'Must contain special character')
    


    Transform Data



    text
    ypescript
    const UserSchema = z.object({
      email: z.string().email().toLowerCase(),
      age: z.string().transform(val => parseInt(val, 10)),
      name: z.string().trim(),
    })
    
    const result = UserSchema.parse({
      email: 'JOHN@EXAMPLE.COM',
      age: '30',
      name: '  John  ',
    })
    // { email: 'john@example.com', age: 30, name: 'John' }
    


    Real-World Examples



    API Response Validation



    text
    ypescript
    const ApiResponseSchema = z.object({
      success: z.boolean(),
      data: z.object({
        users: z.array(UserSchema),
        total: z.number(),
      }),
    })
    
    // Fetch and validate
    async function fetchUsers() {
      const response = await fetch('/api/users')
      const data = await response.json()
      return ApiResponseSchema.parse(data)
    }
    


    Form Validation



    text
    ypescript
    const LoginFormSchema = z.object({
      email: z.string().email('Invalid email'),
      password: z.string().min(8, 'Password too short'),
    })
    
    function handleSubmit(formData: FormData) {
      const result = LoginFormSchema.safeParse({
        email: formData.get('email'),
        password: formData.get('password'),
      })
    
      if (!result.success) {
        return result.error.errors // Show errors to user
      }
    
      // Process form
    }
    


    Advantages



    Over Manual Validation



    | Feature | Manual | Zod |
    |---------|--------|-----|
    | Type Safety | No | Yes |
    | Reusable | No | Yes |
    | Error Messages | Manual | Automatic |
    | Maintainability | Low | High |

    Over Other Libraries

  • Better TypeScript support than Joi
  • Smaller bundle size than Yup
  • Better performance than class-validator
  • More flexible than ts-interface-checker


  • Why Zod?

  • Type Safety: Validate once, type everywhere
  • Developer Experience: Intuitive API
  • Performance: Fast and efficient
  • Zero Dependencies: Lightweight
  • Tree Shakeable: Small bundle size


  • Summary



    Zod is essential for any TypeScript project dealing with external data. Provides runtime validation without sacrificing type safety.




    Rating: 猸愨瓙猸愨瓙猸?
    Best for: TypeScript projects, API validation, forms
    Learning curve: 猸愨瓙
    Bundle size: ~3KB (minified)
    标签:

    💬 评论区 (0)

    暂无评论,快来抢沙发吧!