The Problem

Currently, we have to manually call c.Validate() in every handler:
Issues:
  • ❌ Repetitive code in every handler
  • ❌ Easy to forget to validate
  • ❌ Violates DRY (Don’t Repeat Yourself)

The Solution: Validation Middleware

How It Works

Automatic Model Validation Automatic Model Validation

Implementation

1. Validation Middleware

2. Register Middleware in main.go

3. Simplified Handlers

Before (Manual Validation):
After (Automatic Validation):

How the Middleware Works Internally

Step-by-Step Execution


Context Wrapping Pattern

The Decorator Pattern


Advanced: Conditional Validation

Skip Validation for Certain Routes


Comparison: Manual vs Automatic

Manual Validation (Current)

Pros:
  • ✅ Explicit (you see what’s happening)
  • ✅ Fine-grained control
Cons:
  • ❌ Repetitive code
  • ❌ Easy to forget
  • ❌ Violates DRY
Code:

Automatic Validation (Middleware)

Pros:
  • ✅ DRY (Don’t Repeat Yourself)
  • ✅ Can’t forget to validate
  • ✅ Cleaner handlers
Cons:
  • ⚠️ Less explicit (validation is “hidden”)
  • ⚠️ Slightly harder to debug
Code:

When to Use Each Approach

Use Manual Validation When:

  • You need fine-grained control
  • You want explicit validation for clarity
  • You have conditional validation logic
  • You’re learning the framework

Use Automatic Validation When:

  • You have many endpoints
  • You want consistent validation across all routes
  • You prefer DRY code
  • You’re building a production API

Testing the Middleware

Test 1: Valid Request

Test 2: Invalid Email

Test 3: Missing Field


Alternative Approach: Generic Validator Function

If you don’t want middleware, you can create a helper function:
Pros:
  • ✅ Explicit
  • ✅ Reusable
  • ✅ No middleware magic
Cons:
  • ⚠️ Still need to call it in every handler

Recommendation

  1. Use Automatic Validation Middleware for most routes
    • Cleaner code
    • Consistent validation
    • Less chance of forgetting
  2. Keep Manual Validation for special cases
    • File uploads
    • Webhooks
    • Complex multi-step forms
  3. Document the behavior in API docs
    • Developers should know validation happens automatically

Summary

Automatic Validation Middleware:
  • Wraps echo.Context with a custom context
  • Overrides Bind() to automatically call Validate()
  • Eliminates repetitive c.Validate() calls
  • Makes handlers cleaner and more maintainable