Help us shape the future of Go! Take the 2026 Go Developer Survey

z

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 5 Imported by: 0

README

Zog, a zod inspired schema validation tool

Zog allows user defined schemas for runtime validation, it's also extensible to allow for custom validations and error messages.

Usage

Install
	go get "github.com/SebaPerezBerrios/zog"
Import
import (
	z "github.com/SebaPerezBerrios/zog"
)

Define the base type
type Customer struct {
	ID      int
	Email   string
	Phone   *string
	Address Address
	Account *Account
}

type Address struct {
	ZipCode  string
	City     string
	District string
	Address  string
}

type Account struct {
	ProviderID string
	AccountID  string
	Tokens     []Token
}

type Token struct {
	Data string
}

Define the schema
var CustomerSchema = z.Struct[Customer](
	z.StructSchema{
		"ID":    z.Int().Min(0),
		"Email": z.String(),
		"Phone": z.String().Optional(),
		"Address": z.Struct(z.StructSchema{
			"ZipCode":  z.String().Min(6),
			"City":     z.String().Min(1),
			"District": z.String().Min(1),
			"Address":  z.String().Min(1),
		}, func(address Address) error {
			// further validate address
			return nil
		}),
		"Account": z.Struct[Account](z.StructSchema{
			"ProviderID": z.String().Min(1).Max(3),
			"AccountID":  z.String().Min(1),
			"Tokens": z.Slice[Token]().Min(1).ForEach(z.Struct[Token](z.StructSchema{
				"Data": z.String().Min(1),
			})),
		}).Optional(),
	},
)


Validate
	errors := z.Validate(&customer, CustomerSchema)

Extensible API

You can define custom validation logic by creating new types that embed the core validation struct

type EmailValidation struct {
	z.Validation
}

Then Create builder functions

func EmailValidator() *EmailValidation {
	fns := [](func(string) error){func(email string) error {
		// your validation logic here
		return nil
	}}

	return &EmailValidation{
		Validation: *z.From(reflect.String, fns...),
	}
}

Validation functions

Validations support custom functions that get computed only and after every sub validation has succeeded.

z.Struct(z.StructSchema{
			"ZipCode":  z.String().Min(6),
			"City":     z.String().Min(1),
			"District": z.String().Min(1),
			"Address":  z.String().Min(1),
		}, addressValidation)

Given this schema. addressValidation will only recieve a valid address as defined by the struct schema.

Documentation

Overview

Package z (zog) allows data validation in the form of composable schemas inspired by zod https://zod.dev/, using reflect https://pkg.go.dev/reflect.

CustomerSchema := z.Struct[Customer](

z.StructSchema{
	"ID":    z.Int().Min(0),
	"Email": z.String(),
	"Phone": z.String().Optional(),
	"Address": z.Struct(z.StructSchema{
		"ZipCode":  z.String().Min(6),
		"City":     z.String().Min(1),
		"District": z.String().Min(1),
		"Address":  z.String().Min(1),
	}, func(address Address) error {
		// further validate address
		return nil
	}),
	"Account": z.Struct[Account](z.StructSchema{
		"ProviderID": z.String().Min(1).Max(3),
		"AccountID":  z.String().Min(1),
		"Tokens": z.Slice[Token]().Min(1).ForEach(z.Struct[Token](z.StructSchema{
			"ID": z.String().Min(1),
		})),
	}).Optional(),
},

)

errors := z.Validate(&customer, CustomerSchema)

Using Gin https://gin-gonic.com/

	func (service *Service) testEndpoint(c *gin.Context) error {
		request := dtos.testEndpoint{}

		if err := c.ShouldBind(&request); err != nil {
			return err
		}

		errors := z.Validate(&request, testEndpointDto)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FloatValidation

type FloatValidation struct {
	Validation
}

func Float

func Float(fns ...(func(float64) error)) *FloatValidation

type IntValidation

type IntValidation struct {
	Validation
}

func Int

func Int(fns ...(func(int) error)) *IntValidation

func (IntValidation) Default added in v0.1.5

func (intValidation IntValidation) Default(defaultInt int) *IntValidation

Default Value

func (IntValidation) Max

func (intValidation IntValidation) Max(maxValue int) *IntValidation

func (IntValidation) Min

func (intValidation IntValidation) Min(minValue int) *IntValidation

type SliceValidation

type SliceValidation[T any] struct {
	Validation
}

func Slice

func Slice[T any](fns ...(func([]T) error)) *SliceValidation[T]

func (SliceValidation[T]) ForEach

func (sliceValidation SliceValidation[T]) ForEach(subSchemas ...ValidationI) *SliceValidation[T]

func (SliceValidation[T]) Max

func (sliceValidation SliceValidation[T]) Max(maxLen int) *SliceValidation[T]

func (SliceValidation[T]) Min

func (sliceValidation SliceValidation[T]) Min(minLen int) *SliceValidation[T]

type StringValidation

type StringValidation struct {
	Validation
}

func String

func String(fns ...(func(string) error)) *StringValidation

String builds a string validation schema, accepts a list of validation functions as arguments

func (StringValidation) Default added in v0.1.5

func (stringValidation StringValidation) Default(defaultString string) *StringValidation

Default Value

func (StringValidation) Max

func (stringValidation StringValidation) Max(stringLen int) *StringValidation

Max string length

func (StringValidation) Min

func (stringValidation StringValidation) Min(stringLen int) *StringValidation

Min string length

func (StringValidation) Regex

func (stringValidation StringValidation) Regex(regex *regexp.Regexp) *StringValidation

Regex validation

type StructSchema

type StructSchema = map[string]ValidationI

StructSchema is the type for key value pairs used to validate structs

type StructValidation

type StructValidation[T any] struct {
	Validation
}

func Struct

func Struct[T any](schemaMap StructSchema, fns ...(func(T) error)) *StructValidation[T]

Struct builds a struc validation schema, accepts a map (StructSchema) with key validation pairs.

type Validation

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

func From

func From[T any](reflectKind reflect.Kind, fns ...(func(T) error)) *Validation

From allows for user defined validations, using reflect for type validation, keep in mind that a mismatch between reflect and actual type conversion will result in runtime panic

type CustomStringValidation struct {
	z.Validation
}

func CustomString() *CustomStringValidation {
	fns := [](func(string) error){func(s string) error {
		if s == "ilegal_value" {
			return errors.New("invalid string")
		}
		return nil
	}}

	return &CustomStringValidation{
		Validation: *z.From(reflect.String, fns...),
	}
}

func (Validation) Optional

func (validation Validation) Optional() *Validation

Optional allows for nil pointers to be a valid schema, this allows for optional values to be validated if they are present or skipped if they are a nil pointer

func (Validation) Required

func (validation Validation) Required() *Validation

Required fails the validation on nil pointers (default), see Optional

type ValidationErrorItem

type ValidationErrorItem struct {
	Error string              `json:"error"`
	Path  []string            `json:"path"`
	Kind  ValidationErrorKind `json:"kind"`
}

ValidationErrorItem gives information about validation errors, it implements json marshall (json tags)

func Validate

func Validate[T any](value *T, schema ValidationI) []ValidationErrorItem

Validate takes a struct pointer and a schema, returns the list of validation errors found, an empty list means successful validation

func (ValidationErrorItem) String

func (validationErrorItem ValidationErrorItem) String() string

type ValidationErrorKind

type ValidationErrorKind int
const (
	TypeError ValidationErrorKind = iota
	ValidationError
	FieldError
	NilError
)

func (ValidationErrorKind) String

func (validationErrorKind ValidationErrorKind) String() string

type ValidationI

type ValidationI interface {
	// contains filtered or unexported methods
}

ValidationI is the interface which all sub validators should implement

Jump to

Keyboard shortcuts

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