Go Validator

Go Validator

A lightweight, extensible, and framework-agnostic validation library for Go. Easily validate request bodies, nested objects, and more with a simple and intuitive API.

Features

  • Framework-Agnostic: Works seamlessly with any Go application, not tied to specific frameworks.
  • Customizable Validation Rules: Define and combine multiple validators per field with custom error messages.
  • Support for Nested Structures: Validate complex data structures including maps, slices, and deeply nested structs.
  • Middleware Integration: Includes a Gin adapter for easy integration into Gin-based web applications.
  • Extensibility: Easily extend functionality by creating custom validators.

Why Use go-validator?

The go-validator package offers several compelling reasons to choose it as your validation solution in Go applications:

  • ✅ Lightweight & Efficient: Minimal overhead with robust validation capabilities.
  • ✅ Framework-Agnostic: Works seamlessly across any Go application.
  • ✅ Customizable Validation Rules: Define and combine multiple validators per field effortlessly.
  • ✅ Support for Complex Data Structures: Easily handle nested objects, slices, maps, and structs.
  • ✅ Extensible Architecture: Extend functionality through plugins or custom implementations.
  • ✅ User-Friendly API: Intuitive interface for quick implementation.
  • ✅ Comprehensive Error Messages: Clear error messages for faster debugging.

Installation

Install the latest version of go-validator via:

go get github.com/kthehatter/go-validator/validator

For Gin framework integration, also install the Gin adapter:

go get github.com/kthehatter/go-validator/validator/ginadapter

Note: Ensure you are using Go 1.18+ for compatibility.

Basic Usage

Here’s how you can integrate go-validator into a basic Gin application:

Step 1: Import the Package

Import the core validator package in your Go code:

import "github.com/kthehatter/go-validator/validator"

If you're using Gin, import the Gin adapter as well:

import "github.com/kthehatter/go-validator/validator/ginadapter"

Step 2 : Usage with Gin

Below is an example of how to use go-validator with the Gin framework to validate incoming JSON payloads.

 
package main
 
import (
    "github.com/gin-gonic/gin"
    "github.com/kthehatter/go-validator/validator"
    "github.com/kthehatter/go-validator/validator/ginadapter"
)
 
func main() {
    // Create a new Gin router
    r := gin.New()
 
    // Define validation rules
    validationOptions := []validator.ValidationOption{
        {
            Key:       "username",
            IsOptional: false,
            Validators: []validator.Validator{
                validator.CreateValidator(validator.IsNotEmpty, "Username is required"),
                validator.CreateValidator(validator.IsAlphanumeric, "Username must be alphanumeric"),
            },
        },
        {
            Key:       "email",
            IsOptional: false,
            Validators: []validator.Validator{
                validator.CreateValidator(validator.IsNotEmpty, "Email is required"),
                validator.CreateValidator(validator.IsEmail, "Invalid email address"),
            },
        },
        {
            Key:       "password",
            IsOptional: false,
            Validators: []validator.Validator{
                validator.CreateValidator(validator.IsNotEmpty, "Password is required"),
                validator.CreateValidator(validator.MinLength(6), "Password must be at least 6 characters"),
            },
        },
    }
 
    // Apply the validation middleware to the POST /user endpoint
    r.POST("/user", ginadapter.Middleware(validationOptions), func(c *gin.Context) {
        // Retrieve the validated body from the context
        body := c.MustGet("validatedBody").(gin.H)
 
        // Process the data (for demonstration, just return it)
        c.JSON(200, gin.H{
            "message": "User created successfully",
            "data":    body,
        })
    })
 
    // Start the Gin server
    r.Run(":8080")
}

Step 1: Run the Application

go run main.go

Step 2: Verify the server is running

  • Open a web browser or use curl to send a POST request to http://localhost:8080/user with a JSON body.

Step 3: Test the Endpoint

Test with Valid Data:

curl -X POST http://localhost:8080/user -H "Content-Type: application/json" -d '{
    "username": "user123",
    "email": "user@example.com",
    "password": "password123"
}'

Expected response:

{
    "message": "User created successfully",
    "data": {
        "username": "user123",
        "email": "user@example.com",
        "password": "password123"
    }
}

Test with Invalid Data:

curl -X POST http://localhost:8080/user -H "Content-Type: application/json" -d '{
    "username": "",
    "email": "invalid-email",
    "password": "pass"
}'

Expected response:

{
    "message": "Username is required"
}

Contributing

We welcome contributions! If you find a bug or have an idea for a new feature, please open an issue or submit a pull request.

How to Contribute

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/your-feature-name).
  3. Commit your changes (git commit -m 'Add some feature').
  4. Push to the branch (git push origin feature/your-feature-name).
  5. Open a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.

On this page