valtruc

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2025 License: GPL-3.0 Imports: 4 Imported by: 3

README

Valtruc: structure validator for Go

Valtruc is a simple, zero-dependency structure validator library for Go

Installation

go install github.com/deltegui/valtruc@latest

Basic usage

First add valtruc tags to your structs

type User struct {
    Name string `valtruc:"min=3, max=255, required"`
    Password string `valtruc:"min=3, max=255, required"`
    AcceptConditions bool `valtruc:"mustBeTrue"`
    Email string `valtruc:"min=3, max=255, required"`
}

then create and validate your struct

user := User{
    Name:             "a",
    Password:         "b",
    Email:            "c",
    AcceptConditions: false,
}

errs := vt.Validate(user)

The returned errs is a error array. You can iterate over it and print the error:

for _, err := range errs {
    fmt.Println(err)
}

This code will output:

Validation error on struct 'User', field 'Name' (string) with value 'abcdefghijklmnopqrst': [maxStringLengthIdentifier] the field required maximum length of 10
Validation error on struct 'User', field 'Password' (string) with value 'b': [minStringLengthIdentifier] the field required minimum length of 3
Validation error on struct 'User', field 'AcceptConditions' (bool) with value 'false': [mustBeTrueBoolIdentifier] bool must be true
Validation error on struct 'User', field 'Email' (string) with value 'c': [minStringLengthIdentifier] the field required minimum length of 3

Error API

You can transform the returned error to valtruc.ValidationError type to access all validation error information. The available methods in ValidationError are:

  • GetStructName() string: Gets the struct name (eg. User)
  • GetFieldName() string: Get the validated field name (eg. Email)
  • GetFieldTypeName() string: Get the validated field name (eg. string)
  • GetIdentifier() valtruc.ValidatorIdentifier: Gets an validator identifier (type alias for string). You can use this to programmatically check the error type:
if (err.GetIdentifier() == valtruc.MinFloat64Identifier) {
    // handle error knowing is MinFloat64
}
  • GetFieldValue() string: Get field value as string (eg. 10)
  • GetParam() string: Get validator param (if you have used min validator min=2 the returned string is 2)
  • Error() string
  • Format(str string) string: Formats the error. You can use ${} placeholder to show the param value. (eg. Format("Must be minimum of ${}") will output Must be minimum of 2)

Create your own validators

vt := valtruc.New()

const identifier valtruc.ValidatorIdentifier = "reverseStringIdentifier"

reverse := func(param string) valtruc.Validator {
    return func(ctx valtruc.ValidationContext) (bool, error) {
        str := ctx.FieldValue.String()
        i := 0              // str
        j := len(param) - 1 // param
        for i < len(str) && j >= 0 {
            if param[j] != str[i] {
                return false, valtruc.NewValidationErrorMeta(
                    ctx,
                    "item is not reverse",
                    identifier,
                    param)
            }
            j--
            i++
        }
        return true, nil
    }
}

vt.AddValidator(reflect.String, "reverse", reverse)

usage:

type tag struct {
    Name string `valtruc:"reverse=iawak, min=2"`
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatWithParam added in v1.0.5

func FormatWithParam(str, param string) string

Types

type ValidationContext

type ValidationContext struct {
	StructType reflect.Type
	Field      reflect.StructField
	FieldIndex int
	FieldValue reflect.Value
	Path       []string
}

type ValidationError

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

func NewValidationError

func NewValidationError(
	ctx ValidationContext,
	msg string,
	identifier ValidatorIdentifier,
) ValidationError

func NewValidationErrorMeta

func NewValidationErrorMeta(
	ctx ValidationContext,
	msg string,
	identifier ValidatorIdentifier,
	param string,
) ValidationError

func (ValidationError) Error

func (verr ValidationError) Error() string

func (ValidationError) Format added in v1.0.2

func (verr ValidationError) Format(str string) string

func (ValidationError) GetFieldName

func (verr ValidationError) GetFieldName() string

func (ValidationError) GetFieldTypeName

func (verr ValidationError) GetFieldTypeName() string

func (ValidationError) GetFieldValue

func (verr ValidationError) GetFieldValue() string

func (ValidationError) GetIdentifier added in v1.0.2

func (verr ValidationError) GetIdentifier() ValidatorIdentifier

func (ValidationError) GetParam added in v1.0.2

func (verr ValidationError) GetParam() string

func (ValidationError) GetStructName

func (verr ValidationError) GetStructName() string

func (ValidationError) Path added in v1.3.2

func (err ValidationError) Path() []string

type Validator

type Validator func(ctx ValidationContext) (bool, error)

type ValidatorConstructor

type ValidatorConstructor func(param string) Validator

type ValidatorIdentifier added in v1.0.2

type ValidatorIdentifier string
const (
	MustBeTrueBoolIdentifier  ValidatorIdentifier = "mustBeTrueBoolIdentifier"
	MustBeFalseBoolIdentifier ValidatorIdentifier = "mustBeFalseBoolIdentifier"
)
const (
	MinFloat64Identifier ValidatorIdentifier = "minFloat64Identifier"
	MaxFloat64Identifier ValidatorIdentifier = "maxFloat64Identifier"
)
const (
	MinInt64Identifier ValidatorIdentifier = "minInt64Identifier"
	MaxInt64Identifier ValidatorIdentifier = "maxInt64Identifier"
)
const (
	MinSliceLengthIdentifier ValidatorIdentifier = "minSliceLengthIdentifier"
	MaxSliceLengthIdentifier ValidatorIdentifier = "maxSliceLengthIdentifier"
)
const (
	MinStringLengthIdentifier ValidatorIdentifier = "minStringLengthIdentifier"
	MaxStringLengthIdentifier ValidatorIdentifier = "maxStringLengthIdentifier"
	ContainsStringIdentifier  ValidatorIdentifier = "containsStringIdentifier"
)
const (
	RequiredIdentifier ValidatorIdentifier = "requiredIdentifier"
)

type Valtruc added in v1.0.1

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

func New added in v1.0.1

func New() Valtruc

func (*Valtruc) AddValidator added in v1.0.2

func (vt *Valtruc) AddValidator(forKind reflect.Kind, tagName string, constructor ValidatorConstructor)

func (Valtruc) Validate added in v1.0.1

func (vt Valtruc) Validate(target interface{}) []error

Jump to

Keyboard shortcuts

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