validator

package module
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: MIT Imports: 7 Imported by: 0

README

struct-validator

Verify the values of struct fields using tags

Example code

Use the package with the following URL:

import "codeberg.org/gasior/struct-validator"

And see the below code snippet:

type Test1 struct {
	FirstName     string `validation:"req lenmin:5 lenmax:25"`
	LastName      string `validation:"req lenmin:2 lenmax:50"`
	Age           int    `validation:"req valmin:18 valmax:150"`
	Price         int    `validation:"req valmin:0 valmax:9999"`
	PostCode      string `validation:"req" validation_regexp:"^[0-9][0-9]-[0-9][0-9][0-9]$"`
	Email         string `validation:"req email"`
	BelowZero     int    `validation:"valmin:-6 valmax:-2"`
	DiscountPrice int    `validation:"valmin:0 valmax:8000"`
	Country       string `validation_regexp:"^[A-Z][A-Z]$"`
	County        string `validation:"lenmax:40"`
}

s := &Test1{
	FirstName: "Name that is way too long and certainly not valid",
	...
}

o := validator.&ValidationOptions{
	RestrictFields: map[string]bool{
		"FirstName": true,
		"LastName":  true,
		...
	},
	...
}

isValid, fieldViolations, err := validator.Validate(s, &o)

Documentation

Index

Constants

View Source
const (
	FailLenMin = 2 << iota
	FailLenMax
	FailValMin
	FailValMax
	FailRegExp
	FailEmail
	FailReq
	FailType
)

Variables

This section is empty.

Functions

func Validate

func Validate(obj interface{}, options *ValidateOptions) (bool, map[string]int, error)

Validate takes a struct and validates values of its fields based on their tags.

func ValidateField

func ValidateField(structField reflect.StructField, fieldValue reflect.Value, tagName string) (bool, int)

ValidateField takes a reflected struct field, its value and a tagname and validates the values against the requirements in the tag.

Types

type ValidateOptions

type ValidateOptions struct {
	RestrictFields  map[string]bool
	TagName         string
	OverwriteValues map[string]interface{}
}

ValidateOptions is an optional configuration for validation: * RestrictFields defines what struct fields should be validated * TagName sets tag used to define validation (default is "validation") * OverwriteValues allows overriding values of fields

Jump to

Keyboard shortcuts

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