gozod

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 4 Imported by: 0

README

Gozod - Zod-like Validation Library for Go

Gozod is a powerful, type-safe validation library for Go inspired by Zod, featuring clear error messages and a fluent API.

Features

  • 🎯 Type-safe schemas - Define validation rules with a fluent API
  • 📝 Clear error messages - Human-readable error messages like Zod
  • 🔗 Chainable validators - Build complex validation rules easily
  • 🎨 Multiple data types - String, Int, Float, Bool, Object, Array
  • Nilable support - Handle nilable fields
  • 🗺️ Map to Struct conversion - Validate and convert API payloads to structs
  • 🔍 Flexible validation - Validate maps, structs, or any any
  • 🎨 Custom error messages - Easy customization of error messages
  • 🔧 Custom validation with Refine - Add custom validation logic like Zod's refine
  • 🎯 Advanced validation with SuperRefine - Fine-grained error control with custom paths and codes, similar to Zod's superRefine
  • 📊 Rich error handling - Group, filter, and format errors for API responses
  • 🚀 Zero dependencies - Pure Go, no external dependencies

Installation

go get github.com/0xfurai/gozod

Or use it directly in your project:

import "gozod"

Quick Start

package main

import (
    "encoding/json"
    "fmt"
    "gozod"
)

// Define your struct
type User struct {
    Name     string `json:"name"`
    Email    string `json:"email"`
    Age      int    `json:"age"`
    IsActive bool   `json:"isActive"`
}

func main() {
    // Type-safe schemas - Define validation rules with a fluent API
    userSchema := gozod.Struct(map[string]gozod.Schema{
        "name": gozod.String().
            Min(3).
            Max(50),
        "email": gozod.String().
            Email(),
        "age": gozod.Int().
            Min(18).
            Max(120),
        "isActive": gozod.Bool().Nilable(),
    })

    // Valid user
    validUser := User{
        Name:     "John Doe",
        Email:    "john@example.com",
        Age:      25,
        IsActive: true,
    }

    errors := userSchema.Validate(validUser, nil)
    if errors != nil {
        fmt.Println("Validation failed:", errors.FormatErrors())
    } else {
        fmt.Println("✅ Valid user!")
    }

    // Invalid user (demonstrates error handling)
    invalidUser := User{
        Name:  "Jo",              // Too short (min 3)
        Email: "invalid-email",   // Invalid email format
        Age:   15,                // Too young (min 18)
    }

    errors = userSchema.Validate(invalidUser, nil)
    if errors != nil {
        // Get formatted errors for display
        fmt.Println("\n❌ Validation errors:")
        fmt.Println(errors.FormatErrors())

        // Or get JSON format for API responses
        jsonErrors, _ := json.MarshalIndent(errors.FormatErrorsJSON(), "", "  ")
        fmt.Println("\nJSON format:", string(jsonErrors))
    }
}

Documentation

Running Examples

# Run comprehensive examples
go run examples/main.go

# Or run your own code
go run main.go

License

MIT

Documentation

Index

Constants

View Source
const (
	// ErrCodeRequired indicates a required field is missing
	ErrCodeRequired = "required"

	// ErrCodeInvalidType indicates the value type doesn't match the expected type
	ErrCodeInvalidType = "invalid_type"

	// ErrCodeTooSmall indicates a value is too small (below minimum)
	ErrCodeTooSmall = "too_small"

	// ErrCodeTooBig indicates a value is too big (above maximum)
	ErrCodeTooBig = "too_big"

	// ErrCodeInvalidString indicates a string validation failed (email, URL, regex, etc.)
	ErrCodeInvalidString = "invalid_string"

	// ErrCodeInvalidEnumValue indicates a value is not in the allowed enum values
	ErrCodeInvalidEnumValue = "invalid_enum_value"

	// ErrCodeUnrecognizedKeys indicates unknown keys in strict object validation
	ErrCodeUnrecognizedKeys = "unrecognized_keys"

	// ErrCodeCustomValidation indicates a custom refine validation failed
	ErrCodeCustomValidation = "custom_validation"
)

Error codes for validation errors

Variables

This section is empty.

Functions

func PathAppend

func PathAppend(path []any, part any) []any

PathAppend appends a new part to a path array and returns a new array

func PathEqual

func PathEqual(path1, path2 []any) bool

PathEqual checks if two path arrays are equal

func PathToString

func PathToString(path []any) string

PathToString converts a path array to a string representation e.g., ["user", "email"] -> "user.email", ["test", 1] -> "test[1]"

Types

type ArraySchema

type ArraySchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

ArraySchema validates array/slice values

func Array

func Array(elementSchema Schema) *ArraySchema

Array creates a new array schema

func (*ArraySchema) CustomError

func (s *ArraySchema) CustomError(code, message string) *ArraySchema

CustomError sets a custom error message for a specific error code

func (*ArraySchema) Max

func (s *ArraySchema) Max(length int) *ArraySchema

Max sets the maximum length

func (*ArraySchema) Min

func (s *ArraySchema) Min(length int) *ArraySchema

Min sets the minimum length

func (*ArraySchema) Nilable

func (s *ArraySchema) Nilable() *ArraySchema

Nilable allows null values

func (*ArraySchema) NonEmpty

func (s *ArraySchema) NonEmpty() *ArraySchema

NonEmpty validates that the array is not empty

func (*ArraySchema) Refine

func (s *ArraySchema) Refine(validator RefineFunc) *ArraySchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*ArraySchema) SetErrorFormatter

func (s *ArraySchema) SetErrorFormatter(formatter CustomErrorFunc) *ArraySchema

SetErrorFormatter sets a custom error formatter function

func (*ArraySchema) SuperRefine

func (s *ArraySchema) SuperRefine(validator SuperRefineFunc) *ArraySchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*ArraySchema) Type

func (s *ArraySchema) Type() string

Type returns the schema type

func (*ArraySchema) Validate

func (s *ArraySchema) Validate(value any, path []any) *ValidationErrors

Validate validates a value against the array schema

type BaseSchema

type BaseSchema struct {
	// contains filtered or unexported fields
}

BaseSchema provides common functionality for all schemas

type BoolSchema

type BoolSchema struct {
	BaseSchema
}

BoolSchema validates boolean values

func Bool

func Bool() *BoolSchema

Bool creates a new boolean schema

func (*BoolSchema) CustomError

func (s *BoolSchema) CustomError(code, message string) *BoolSchema

CustomError sets a custom error message for a specific error code

func (*BoolSchema) Nilable

func (s *BoolSchema) Nilable() *BoolSchema

Nilable allows null values

func (*BoolSchema) Refine

func (s *BoolSchema) Refine(validator RefineFunc) *BoolSchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*BoolSchema) SetErrorFormatter

func (s *BoolSchema) SetErrorFormatter(formatter CustomErrorFunc) *BoolSchema

SetErrorFormatter sets a custom error formatter function

func (*BoolSchema) SuperRefine

func (s *BoolSchema) SuperRefine(validator SuperRefineFunc) *BoolSchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*BoolSchema) Type

func (s *BoolSchema) Type() string

Type returns the schema type

func (*BoolSchema) Validate

func (s *BoolSchema) Validate(value any, path []any) *ValidationErrors

Validate validates a value against the boolean schema

type CustomErrorFunc

type CustomErrorFunc func(path []any, code, defaultMessage string) string

CustomErrorFunc is a function type for custom error formatting The path parameter is now a []any array

type FlattenErrorResult

type FlattenErrorResult struct {
	FormErrors  []string            `json:"formErrors"`
	FieldErrors map[string][]string `json:"fieldErrors"`
}

FlattenErrorResult represents the flattened error structure

type FloatSchema

type FloatSchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

FloatSchema validates float values

func Float

func Float() *FloatSchema

Float creates a new float schema

func (*FloatSchema) CustomError

func (s *FloatSchema) CustomError(code, message string) *FloatSchema

CustomError sets a custom error message for a specific error code for FloatSchema

func (*FloatSchema) Max

func (s *FloatSchema) Max(value float64) *FloatSchema

Max sets the maximum value for FloatSchema

func (*FloatSchema) Min

func (s *FloatSchema) Min(value float64) *FloatSchema

Min sets the minimum value for FloatSchema

func (*FloatSchema) MultipleOf

func (s *FloatSchema) MultipleOf(value float64) *FloatSchema

MultipleOf validates that the number is a multiple of the given value for FloatSchema

func (*FloatSchema) Negative

func (s *FloatSchema) Negative() *FloatSchema

Negative validates that the number is negative (< 0) for FloatSchema

func (*FloatSchema) Nilable

func (s *FloatSchema) Nilable() *FloatSchema

Nilable allows null values for FloatSchema

func (*FloatSchema) NonNegative

func (s *FloatSchema) NonNegative() *FloatSchema

NonNegative validates that the number is non-negative (>= 0) for FloatSchema

func (*FloatSchema) NonPositive

func (s *FloatSchema) NonPositive() *FloatSchema

NonPositive validates that the number is non-positive (<= 0) for FloatSchema

func (*FloatSchema) Positive

func (s *FloatSchema) Positive() *FloatSchema

Positive validates that the number is positive (> 0) for FloatSchema

func (*FloatSchema) Refine

func (s *FloatSchema) Refine(validator RefineFunc) *FloatSchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*FloatSchema) SetErrorFormatter

func (s *FloatSchema) SetErrorFormatter(formatter CustomErrorFunc) *FloatSchema

SetErrorFormatter sets a custom error formatter function for FloatSchema

func (*FloatSchema) SuperRefine

func (s *FloatSchema) SuperRefine(validator SuperRefineFunc) *FloatSchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*FloatSchema) Type

func (s *FloatSchema) Type() string

Type returns the schema type for FloatSchema

func (*FloatSchema) Validate

func (s *FloatSchema) Validate(value any, path []any) *ValidationErrors

Validate validates a value against the float schema

type IntSchema

type IntSchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

IntSchema validates integer values

func Int

func Int() *IntSchema

Int creates a new integer schema

func (*IntSchema) CustomError

func (s *IntSchema) CustomError(code, message string) *IntSchema

CustomError sets a custom error message for a specific error code for IntSchema

func (*IntSchema) Max

func (s *IntSchema) Max(value int64) *IntSchema

Max sets the maximum value for IntSchema

func (*IntSchema) Min

func (s *IntSchema) Min(value int64) *IntSchema

Min sets the minimum value for IntSchema

func (*IntSchema) MultipleOf

func (s *IntSchema) MultipleOf(value int64) *IntSchema

MultipleOf validates that the number is a multiple of the given value for IntSchema

func (*IntSchema) Negative

func (s *IntSchema) Negative() *IntSchema

Negative validates that the number is negative (< 0) for IntSchema

func (*IntSchema) Nilable

func (s *IntSchema) Nilable() *IntSchema

Nilable allows null values for IntSchema

func (*IntSchema) NonNegative

func (s *IntSchema) NonNegative() *IntSchema

NonNegative validates that the number is non-negative (>= 0) for IntSchema

func (*IntSchema) NonPositive

func (s *IntSchema) NonPositive() *IntSchema

NonPositive validates that the number is non-positive (<= 0) for IntSchema

func (*IntSchema) Positive

func (s *IntSchema) Positive() *IntSchema

Positive validates that the number is positive (> 0) for IntSchema

func (*IntSchema) Refine

func (s *IntSchema) Refine(validator RefineFunc) *IntSchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*IntSchema) SetErrorFormatter

func (s *IntSchema) SetErrorFormatter(formatter CustomErrorFunc) *IntSchema

SetErrorFormatter sets a custom error formatter function for IntSchema

func (*IntSchema) SuperRefine

func (s *IntSchema) SuperRefine(validator SuperRefineFunc) *IntSchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*IntSchema) Type

func (s *IntSchema) Type() string

Type returns the schema type for IntSchema

func (*IntSchema) Validate

func (s *IntSchema) Validate(value any, path []any) *ValidationErrors

Validate validates a value against the int schema

type MapSchema

type MapSchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

MapSchema validates object/map values

func Map

func Map(shape map[string]Schema) *MapSchema

Map creates a new object/map schema

func (*MapSchema) CustomError

func (s *MapSchema) CustomError(code, message string) *MapSchema

CustomError sets a custom error message for a specific error code

func (*MapSchema) Nilable

func (s *MapSchema) Nilable() *MapSchema

Nilable allows null values

func (*MapSchema) Refine

func (s *MapSchema) Refine(validator RefineFunc) *MapSchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*MapSchema) SetErrorFormatter

func (s *MapSchema) SetErrorFormatter(formatter CustomErrorFunc) *MapSchema

SetErrorFormatter sets a custom error formatter function

func (*MapSchema) Strict

func (s *MapSchema) Strict() *MapSchema

Strict rejects unknown keys

func (*MapSchema) SuperRefine

func (s *MapSchema) SuperRefine(validator SuperRefineFunc) *MapSchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*MapSchema) Type

func (s *MapSchema) Type() string

Type returns the schema type

func (*MapSchema) Validate

func (s *MapSchema) Validate(value any, path []any) *ValidationErrors

Validate validates a value against the object schema

type RefineFunc

type RefineFunc func(value any) (bool, string)

RefineFunc is a function type for custom validation refinement Returns true if validation passes, false otherwise The second return value is the error message (optional, can be empty string)

type Schema

type Schema interface {
	Validate(value any, path []any) *ValidationErrors
	Type() string
}

Schema is the base interface for all schemas

type Shape

type Shape map[string]Schema

Shape defines the structure of a struct schema Maps struct field names (or JSON tag names) to validation schemas

type StringSchema

type StringSchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

StringSchema validates string values

func String

func String() *StringSchema

String creates a new string schema

func (*StringSchema) CustomError

func (s *StringSchema) CustomError(code, message string) *StringSchema

CustomError sets a custom error message for a specific error code This can be called on any schema type to customize error messages

func (*StringSchema) Email

func (s *StringSchema) Email() *StringSchema

Email validates email format

func (*StringSchema) EndsWith

func (s *StringSchema) EndsWith(suffix string) *StringSchema

EndsWith validates that the string ends with the given suffix

func (*StringSchema) Includes

func (s *StringSchema) Includes(substring string) *StringSchema

Includes validates that the string includes the given substring

func (*StringSchema) Max

func (s *StringSchema) Max(length int) *StringSchema

Max sets the maximum length

func (*StringSchema) Min

func (s *StringSchema) Min(length int) *StringSchema

Min sets the minimum length

func (*StringSchema) Nilable

func (s *StringSchema) Nilable() *StringSchema

Nilable allows null values

func (*StringSchema) NotOneOf

func (s *StringSchema) NotOneOf(options ...string) *StringSchema

NotOneOf validates that the value is not one of the provided options

func (*StringSchema) OneOf

func (s *StringSchema) OneOf(options ...string) *StringSchema

OneOf validates that the value is one of the provided options

func (*StringSchema) Refine

func (s *StringSchema) Refine(validator RefineFunc) *StringSchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*StringSchema) Regex

func (s *StringSchema) Regex(pattern string, message ...string) *StringSchema

Regex validates against a regular expression

func (*StringSchema) SetErrorFormatter

func (s *StringSchema) SetErrorFormatter(formatter CustomErrorFunc) *StringSchema

SetErrorFormatter sets a custom error formatter function The formatter receives (path, code, defaultMessage) and returns the formatted message

func (*StringSchema) StartsWith

func (s *StringSchema) StartsWith(prefix string) *StringSchema

StartsWith validates that the string starts with the given prefix

func (*StringSchema) SuperRefine

func (s *StringSchema) SuperRefine(validator SuperRefineFunc) *StringSchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*StringSchema) Type

func (s *StringSchema) Type() string

Type returns the schema type

func (*StringSchema) URL

func (s *StringSchema) URL() *StringSchema

URL validates URL format

func (*StringSchema) Validate

func (s *StringSchema) Validate(value any, path []any) *ValidationErrors

Validate validates a value against the string schema

type StructSchema

type StructSchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

StructSchema validates struct values directly

func Struct

func Struct(shape Shape) *StructSchema

Struct creates a new struct schema The shape maps struct field names (or JSON tag names) to validation schemas

func (*StructSchema) CustomError

func (s *StructSchema) CustomError(code, message string) *StructSchema

CustomError sets a custom error message for a specific error code

func (*StructSchema) Nilable

func (s *StructSchema) Nilable() *StructSchema

Nilable allows null/nil values

func (*StructSchema) Refine

func (s *StructSchema) Refine(validator RefineFunc) *StructSchema

Refine adds a custom validation function The function receives the value and returns (isValid, errorMessage) If isValid is false, validation fails with the provided errorMessage If errorMessage is empty, a default message will be used

func (*StructSchema) SetErrorFormatter

func (s *StructSchema) SetErrorFormatter(formatter CustomErrorFunc) *StructSchema

SetErrorFormatter sets a custom error formatter function

func (*StructSchema) Strict

func (s *StructSchema) Strict() *StructSchema

Strict rejects unknown fields

func (*StructSchema) SuperRefine

func (s *StructSchema) SuperRefine(validator SuperRefineFunc) *StructSchema

SuperRefine adds a super refinement validation function Similar to Refine, but provides a context object for adding errors with custom paths and codes This allows for more fine-grained control over error reporting, similar to Zod's superRefine

func (*StructSchema) Type

func (s *StructSchema) Type() string

Type returns the schema type

func (*StructSchema) Validate

func (s *StructSchema) Validate(value any, path []any) *ValidationErrors

Validate validates a struct value against the schema

type SuperRefineContext

type SuperRefineContext struct {
	// contains filtered or unexported fields
}

SuperRefineContext provides methods to add validation errors with custom paths and codes Similar to Zod's superRefine context, allowing fine-grained control over error reporting

func (*SuperRefineContext) AddIssue

func (ctx *SuperRefineContext) AddIssue(path []any, code, message string)

AddIssue adds a validation error with a custom path, code, and message The path is relative to the base path of the schema being validated

func (*SuperRefineContext) AddIssueWithMeta

func (ctx *SuperRefineContext) AddIssueWithMeta(path []any, code, message string, meta map[string]any)

AddIssueWithMeta adds a validation error with metadata

type SuperRefineFunc

type SuperRefineFunc func(value any, ctx *SuperRefineContext)

SuperRefineFunc is a function type for super refinement validation Provides access to a context object for adding errors with custom paths and codes

type ValidationError

type ValidationError struct {
	Path    []any          // Field path as array of path parts (e.g., ["user", "email"] or ["test", 1])
	Message string         // Human-readable error message
	Code    string         // Error code (use constants like ErrCodeTooSmall, ErrCodeInvalidType, etc.)
	Meta    map[string]any // Additional metadata for the error
}

ValidationError represents a single validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface

type ValidationErrors

type ValidationErrors struct {
	Errors []ValidationError
}

ValidationErrors is a collection of validation errors

func (*ValidationErrors) Add

func (e *ValidationErrors) Add(path []any, code, message string)

Add adds a new validation error

func (*ValidationErrors) AddWithMeta

func (e *ValidationErrors) AddWithMeta(path []any, code, message string, meta map[string]any)

AddWithMeta adds a new validation error with metadata

func (*ValidationErrors) Error

func (e *ValidationErrors) Error() string

Error implements the error interface

func (*ValidationErrors) Flatten

func (e *ValidationErrors) Flatten() FlattenErrorResult

Flatten returns errors in a flattened format with formErrors and fieldErrors formErrors contains errors without a specific field path (empty path) fieldErrors contains errors grouped by field path Array element errors (e.g., test[0], test[1]) are grouped under the base field name (e.g., test)

func (*ValidationErrors) FormatErrors

func (e *ValidationErrors) FormatErrors() string

FormatErrors returns a formatted string of all errors

func (*ValidationErrors) FormatErrorsJSON

func (e *ValidationErrors) FormatErrorsJSON() map[string]any

FormatErrorsJSON returns errors in a structured format (for API responses)

func (*ValidationErrors) GetErrorsByCode

func (e *ValidationErrors) GetErrorsByCode(code string) []ValidationError

GetErrorsByCode returns all errors with a specific code

func (*ValidationErrors) GetErrorsByPath

func (e *ValidationErrors) GetErrorsByPath(path []any) []ValidationError

GetErrorsByPath returns all errors for a specific path

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL