validator

package module
v2.10.4 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: BSD-3-Clause Imports: 24 Imported by: 0

README

validator.go

CI Coverage Go Reference Go Report Card GitHub Release License

A Go validation library with composable rules, nested struct support, and detailed error reporting.

Installation

go get github.com/raoptimus/validator.go/v2

Usage

Validate a single value
import validator "github.com/raoptimus/validator.go/v2"

ctx := context.Background()

err := validator.ValidateValue(ctx, "user@example.com",
    validator.NewRequired(),
    validator.NewEmail(),
)
// err == nil
Validate a struct

Field names in RuleSet must match struct field names. Error paths use json tags as aliases.

type SignUpRequest struct {
    Email string `json:"email"`
    Name  string `json:"name"`
    Age   int    `json:"age"`
}

req := SignUpRequest{
    Email: "bad-email",
    Name:  "",
    Age:   200,
}

err := validator.Validate(ctx, &req, validator.RuleSet{
    "Email": {validator.NewRequired(), validator.NewEmail()},
    "Name":  {validator.NewRequired(), validator.NewStringLength(1, 100)},
    "Age":   {validator.NewRequired(), validator.NewNumber(1, 150)},
})

// err.Error() == "email: Email is not a valid email. name: Value cannot be blank. age: Value must be no greater than 150."
Validate a map
data := map[string]any{
    "count": 0,
}

err := validator.Validate(ctx, data, validator.RuleSet{
    "count": {
        validator.NewRequired(),
        validator.NewNumber(1, 100),
    },
})
Nested structs
type Address struct {
    City   string `json:"city"`
    Street string `json:"street"`
}

type User struct {
    Name    string  `json:"name"`
    Address Address `json:"address"`
}

err := validator.Validate(ctx, &User{Name: "Alice"}, validator.RuleSet{
    "Name": {validator.NewRequired()},
    "Address": {
        validator.NewNested(validator.RuleSet{
            "City":   {validator.NewRequired()},
            "Street": {validator.NewRequired(), validator.NewStringLength(1, 255)},
        }),
    },
})

// Errors have dotted paths: "address.city", "address.street"
Validate each element in a slice
err := validator.ValidateValue(ctx, []string{"ok", "", "fine"},
    validator.NewEach(validator.NewStringLength(1, 255)),
)

// Error path: "1" (index of the empty string)
Conditional validation
validator.NewEmail().When(func(ctx context.Context, value any) bool {
    return value != nil && value.(string) != ""
})
Skip on empty / skip on error
// Skip email format check if the value is empty
validator.NewEmail().SkipOnEmpty()

// Skip this rule if a previous rule already failed
validator.NewStringLength(1, 100).SkipOnError()
OR rule

At least one of the rules must pass:

validator.NewOR("Must be a valid email or URL",
    validator.NewEmail(),
    validator.NewURL(),
)
Custom callback
validator.NewCallback(func(ctx context.Context, value string) error {
    if strings.Contains(value, "forbidden") {
        return validator.NewValidationError("Value contains forbidden word.")
    }
    return nil
})
Error handling
err := validator.Validate(ctx, &req, rules)
if err != nil {
    var result validator.Result
    if errors.As(err, &result) {
        // Map of field path -> error messages
        errorMap := result.ErrorMessagesIndexedByPath()
        // e.g. {"email": ["Email is not a valid email."], "age": ["Value must be no greater than 150."]}
    }
}
Multilanguage support

Validation messages are translated automatically based on the language in context. Built-in languages: English (en, default) and Russian (ru).

// Set language in context
ctx := validator.WithLanguage(context.Background(), validator.LanguageRU)

err := validator.ValidateValue(ctx, "", validator.NewRequired())
// err.Error() == "Значение не должно быть пустым."
HTTP middleware example
func LangMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        lang := r.Header.Get("Accept-Language") // "ru", "en", etc.
        ctx := validator.WithLanguage(r.Context(), validator.Language(lang))
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Now any validator call inside the handler will use the language from the request:

func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
    var req CreateRequest
    // ... decode request body ...

    // language is already in r.Context() from the middleware
    err := validator.Validate(r.Context(), &req, validator.RuleSet{
        "Name": {validator.NewRequired()},
    })
    // Accept-Language: ru → "Значение не должно быть пустым."
    // Accept-Language: en → "Value cannot be blank."
}
Register a custom language
func init() {
    validator.Translations.Register(validator.Language("es"), map[string]string{
        validator.MessageRequired: "El valor no puede estar vacío.",
        validator.MessageTooShort: "El valor debe contener al menos {min} caracteres.",
        // ...
    })
}
Check for missing translations
missing := validator.Translations.Missing(validator.Language("es"))
// returns a list of message IDs without translation for the given language
Use DummyTranslator (no translation, placeholder replacement only)
validator.SetTranslator(&validator.DummyTranslator{})

Available Rules

Rule Description
Required Value must not be empty
Number Integer within min/max range
StringLength UTF-8 string length within min/max
Email Valid email format
URL Valid URL format
IP Valid IP address
UUID Valid UUID format
MAC Valid MAC address
MSISDN Valid mobile phone number
OGRN Valid Russian OGRN number
JSON Valid JSON structure
SQL Valid SQL statement
MatchRegularExpression Matches a custom regex
In Value is in a predefined set
InRange Numeric value within a range
Compare Compare against another value (==, !=, <, >, <=, >=)
Nested Validate nested struct fields
Each Validate each element in a slice/array
OR At least one rule must pass
Callback Custom validation function
UniqueValues All elements in a slice are unique
NumericString String is a valid numeric representation
HumanText Valid human-readable text
ImageMeta Image metadata validation
Time Time format and range validation

License

BSD 3-Clause

Documentation

Overview

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

Index

Constants

View Source
const (
	OperatorEqual            = "=="
	OperatorNotEqual         = "!="
	OperatorGreaterThan      = ">"
	OperatorGreaterThanEqual = ">="
	OperatorLessThan         = "<"
	OperatorLessThanEqual    = "<="
)
View Source
const (
	ImageMimeTypePNG = "image/png"
	ImageMimeTypeJPG = "image/jpeg"
	ImageMimeTypeGIF = "image/gif"
)
View Source
const (
	// Required
	MessageRequired = "Value cannot be blank."

	// StringLength
	MessageStringType = "This value must be a string."
	MessageTooShort   = "This value should contain at least {min}."
	MessageTooLong    = "This value should contain at most {max}."

	// Compare
	MessageCompareEqual            = "Value must be equal to '{targetValueOrAttribute}'."
	MessageCompareNotEqual         = "Value must not be equal to '{targetValueOrAttribute}'."
	MessageCompareGreaterThan      = "Value must be greater than '{targetValueOrAttribute}'"
	MessageCompareGreaterThanEqual = "Value must be greater than or equal to '{targetValueOrAttribute}'"
	MessageCompareLessThan         = "Value must be less than '{targetValueOrAttribute}'"
	MessageCompareLessThanEqual    = "Value must be less than or equal to '{targetValueOrAttribute}'"

	// Number
	MessageNotNumber      = "Value must be a number."
	MessageNumberTooBig   = "Value must be no greater than {max}."
	MessageNumberTooSmall = "Value must be no less than {min}."

	// Numeric
	MessageNotNumeric = "Value must be a numeric."

	// URL
	MessageInvalidURL      = "This value is not a valid URL."
	MessageInvalidDeepLink = "This value is not a valid deep link url."

	// IP
	MessageInvalidIP      = "Must be a valid IP address."
	MessageIPv4NotAllowed = "Must not be an IPv4 address."
	MessageIPv6NotAllowed = "Must not be an IPv6 address."

	// UUID
	MessageInvalidUUID        = "Invalid UUID format."
	MessageInvalidUUIDVersion = "UUID version must be equal to {version}."

	// JSON
	MessageInvalidJSON = "Must be a valid JSON"

	// MAC
	MessageInvalidMAC = "Must be a valid MAC address."

	// MatchRegularExpression
	MessageValueInvalid = "Value is invalid."

	// Generic (used by Time, Each)
	MessageInvalid = "Value is invalid"

	// Email
	MessageInvalidEmail = "Email is not a valid email."

	// Time
	MessageTimeFormat   = "Format of the time value must be equal {format}"
	MessageTimeTooBig   = "Time must be no greater than {max}."
	MessageTimeTooSmall = "Time must be no less than {min}."

	// ImageMeta
	MessageInvalidImageMeta = "This value must be a ImageMetaData struct."
	MessageInvalidMimeType  = "MimeType must be a equal one of [{mimeTypes}]."
	MessageFileTooLarge     = "File size must be greater than {maxFileSizeBytes} bytes."

	// InRange
	MessageInRangeInvalid = "This value is invalid"

	// Each
	MessageEachIncorrectInput = "Value must be array"

	// UniqueValues
	MessageUniqueValues = "The list of values must be unique."

	// OGRN
	MessageInvalidOGRN       = "This value is not a valid OGRN."
	MessageInvalidOGRNIP     = "This value is not a valid OGRNIP."
	MessageInvalidOGRNLength = "This value should contain either 13 or 15 characters."

	// SQL
	MessageInvalidSQL = "Value is invalid sql."

	// MSISDN
	MessageInvalidMSISDN = "MSISDN format is invalid."

	// HumanText
	MessageInvalidHumanText = "This value must be a normal text."

	// Nested
	MessageNestedNotStruct = "value should be a struct. %T given."
)
View Source
const AllowAnyURLSchema = "*"
View Source
const (
	NestedShortcut = "*"
)

Variables

View Source
var (
	ErrNotExistsDataSetIntoContext = errors.New("not exists data set into context")
	ErrUnknownOperator             = errors.New("unknown operator")
	ErrCallbackUnexpectedValueType = errors.New("callback unexpected value type")
)
View Source
var Translations = NewTranslationCatalog()

Functions

func DataSetFromContext

func DataSetFromContext[T DataSet](ctx *Context) (T, bool)

func ExtractDataSet

func ExtractDataSet[T any](ctx context.Context) (T, bool)

func IsError

func IsError(err error) (map[string][]string, bool)

IsError - проверяет на ошибку валидации и возвращает аттрибуты, где ключ равняется полю, а значения ошибкам валидации.

{
	"client_id": [
		"Value cannot be blank.",
		"Value is invalid."
	]
}

func NestedDataSetFromContext

func NestedDataSetFromContext[T any](ctx context.Context) (T, bool)

func PrevNestedDataSetFromContext

func PrevNestedDataSetFromContext[T any](ctx context.Context) (T, bool)

func RootDataSetFromContext

func RootDataSetFromContext[T any](ctx context.Context) (T, bool)

func SetTranslator

func SetTranslator(t Translator)

func Validate

func Validate(ctx context.Context, dataSet any, rules RuleSet) error

func ValidateValue

func ValidateValue(ctx context.Context, value any, rules ...Rule) error

func WithLanguage added in v2.10.0

func WithLanguage(ctx context.Context, lang Language) context.Context

Types

type Callback

type Callback[T any] struct {
	// contains filtered or unexported fields
}

func NewCallback

func NewCallback[T any](f CallbackFunc[T]) *Callback[T]

func (*Callback[T]) SkipOnEmpty

func (r *Callback[T]) SkipOnEmpty() *Callback[T]

func (*Callback[T]) SkipOnError

func (r *Callback[T]) SkipOnError() *Callback[T]

func (*Callback[T]) ValidateValue

func (c *Callback[T]) ValidateValue(ctx context.Context, value any) error

func (*Callback[T]) When

func (r *Callback[T]) When(v WhenFunc) *Callback[T]

type CallbackFunc

type CallbackFunc[T any] func(ctx context.Context, value T) error

type CatalogTranslator added in v2.10.0

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

func NewCatalogTranslator added in v2.10.0

func NewCatalogTranslator(catalog *TranslationCatalog) *CatalogTranslator

func (*CatalogTranslator) Translate added in v2.10.0

func (t *CatalogTranslator) Translate(ctx context.Context, id string, params map[string]any) string

type Compare

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

func NewCompare

func NewCompare(targetValue any, targetAttribute, operator string) *Compare

func (*Compare) SkipOnEmpty

func (r *Compare) SkipOnEmpty() *Compare

func (*Compare) SkipOnError

func (r *Compare) SkipOnError() *Compare

func (*Compare) ValidateValue

func (r *Compare) ValidateValue(ctx context.Context, value any) error

func (*Compare) When

func (r *Compare) When(v WhenFunc) *Compare

func (*Compare) WithMessage

func (r *Compare) WithMessage(v string) *Compare

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

func NewContext

func NewContext(ctx context.Context) *Context

func (*Context) Value

func (c *Context) Value(key any) any

type DataSet

type DataSet interface {
	FieldValue(name string) (any, error)
	FieldAliasName(name string) string
	Name() set.Name
	Data() any
}

type DeepLinkURL

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

func NewDeepLinkURL

func NewDeepLinkURL() *DeepLinkURL

func (*DeepLinkURL) SkipOnEmpty

func (r *DeepLinkURL) SkipOnEmpty() *DeepLinkURL

func (*DeepLinkURL) SkipOnError

func (r *DeepLinkURL) SkipOnError() *DeepLinkURL

func (*DeepLinkURL) ValidateValue

func (r *DeepLinkURL) ValidateValue(_ context.Context, value any) error

func (*DeepLinkURL) When

func (r *DeepLinkURL) When(v WhenFunc) *DeepLinkURL

func (*DeepLinkURL) WithInvalidSchemes

func (r *DeepLinkURL) WithInvalidSchemes(schemes []string) *DeepLinkURL

func (*DeepLinkURL) WithMessage

func (r *DeepLinkURL) WithMessage(message string) *DeepLinkURL

type DummyTranslator

type DummyTranslator struct {
}

func (*DummyTranslator) Translate

func (d *DummyTranslator) Translate(_ context.Context, id string, params map[string]any) string

type Each

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

func NewEach

func NewEach(rules ...Rule) *Each

func (*Each) SkipOnEmpty

func (r *Each) SkipOnEmpty() *Each

func (*Each) SkipOnError

func (r *Each) SkipOnError() *Each

func (*Each) ValidateValue

func (r *Each) ValidateValue(ctx context.Context, value any) error

func (*Each) When

func (r *Each) When(v WhenFunc) *Each

func (*Each) WithIncorrectInputMessage

func (r *Each) WithIncorrectInputMessage(incorrectInputMessage string) *Each

func (*Each) WithMessage

func (r *Each) WithMessage(message string) *Each

type Email

type Email struct {
	*MatchRegularExpression
}

func NewEmail

func NewEmail() *Email

type HumanText

type HumanText struct {
	*MatchRegularExpression
}

func NewHumanText

func NewHumanText() *HumanText

type IP

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

func NewIP

func NewIP() *IP

func (*IP) SkipOnEmpty

func (r *IP) SkipOnEmpty() *IP

func (*IP) SkipOnError

func (r *IP) SkipOnError() *IP

func (*IP) ValidateValue

func (r *IP) ValidateValue(_ context.Context, value any) error

func (*IP) When

func (r *IP) When(v WhenFunc) *IP

func (*IP) WithMessage

func (r *IP) WithMessage(v string) *IP

type ImageMeta

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

func NewImageMeta

func NewImageMeta() *ImageMeta

func (*ImageMeta) SkipOnEmpty

func (r *ImageMeta) SkipOnEmpty() *ImageMeta

func (*ImageMeta) SkipOnError

func (r *ImageMeta) SkipOnError() *ImageMeta

func (*ImageMeta) ValidateValue

func (r *ImageMeta) ValidateValue(_ context.Context, value any) error

func (*ImageMeta) When

func (r *ImageMeta) When(v WhenFunc) *ImageMeta

func (*ImageMeta) WithMessage

func (r *ImageMeta) WithMessage(message string) *ImageMeta

type ImageMetaData

type ImageMetaData struct {
	Name     string
	MimeType string
	Size     uint64
	Width    int
	Height   int
}

type InRange

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

func NewInRange

func NewInRange(rangeValues []any) *InRange

func (*InRange) Not

func (r *InRange) Not() *InRange

func (*InRange) SkipOnEmpty

func (r *InRange) SkipOnEmpty() *InRange

func (*InRange) SkipOnError

func (r *InRange) SkipOnError() *InRange

func (*InRange) ValidateValue

func (r *InRange) ValidateValue(_ context.Context, value any) error

func (*InRange) When

func (r *InRange) When(v WhenFunc) *InRange

func (*InRange) WithMessage

func (r *InRange) WithMessage(message string) *InRange

type JSON

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

func NewJSON

func NewJSON() *JSON

func (*JSON) SkipOnEmpty

func (j *JSON) SkipOnEmpty() *JSON

func (*JSON) SkipOnError

func (j *JSON) SkipOnError() *JSON

func (*JSON) ValidateValue

func (j *JSON) ValidateValue(_ context.Context, value any) error

func (*JSON) When

func (j *JSON) When(v WhenFunc) *JSON

type Key

type Key uint8
const (
	KeyDataSet Key = iota + 1
	KeyPreviousRulesErrored
	KeyRootDataSet
	KeyNestedDataSet
	KeyPrevNestedDataSet
)

type Language added in v2.10.0

type Language string
const (
	LanguageEN Language = "en"
	LanguageRU Language = "ru"
)

func LanguageFromContext added in v2.10.0

func LanguageFromContext(ctx context.Context) Language

type MAC

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

func NewMAC

func NewMAC() *MAC

func (*MAC) SkipOnEmpty

func (m *MAC) SkipOnEmpty() *MAC

func (*MAC) SkipOnError

func (m *MAC) SkipOnError() *MAC

func (*MAC) ValidateValue

func (m *MAC) ValidateValue(_ context.Context, value any) error

func (*MAC) When

func (m *MAC) When(v WhenFunc) *MAC

func (*MAC) WithMessage

func (m *MAC) WithMessage(v string) *MAC

type MSISDN

type MSISDN struct {
	*MatchRegularExpression
}

func NewMSISDN

func NewMSISDN() MSISDN

type MatchRegularExpression

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

func NewMatchRegularExpression

func NewMatchRegularExpression(pattern string) *MatchRegularExpression

func (*MatchRegularExpression) SkipOnEmpty

func (*MatchRegularExpression) SkipOnError

func (*MatchRegularExpression) ValidateValue

func (r *MatchRegularExpression) ValidateValue(_ context.Context, value any) error

func (*MatchRegularExpression) When

func (*MatchRegularExpression) WithMessage

func (r *MatchRegularExpression) WithMessage(message string) *MatchRegularExpression

func (*MatchRegularExpression) WithPattern

func (r *MatchRegularExpression) WithPattern(pattern string) *MatchRegularExpression

type Nested

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

func NewNested

func NewNested(rules RuleSet) *Nested

func (*Nested) SkipOnEmpty

func (r *Nested) SkipOnEmpty() *Nested

func (*Nested) SkipOnError

func (r *Nested) SkipOnError() *Nested

func (*Nested) ValidateValue

func (r *Nested) ValidateValue(ctx context.Context, value any) error

func (*Nested) When

func (r *Nested) When(v WhenFunc) *Nested

func (*Nested) WithMessage

func (r *Nested) WithMessage(message string) *Nested

type Number

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

func NewNumber

func NewNumber(minVal, maxVal int64) *Number

func (*Number) SkipOnEmpty

func (r *Number) SkipOnEmpty() *Number

func (*Number) SkipOnError

func (r *Number) SkipOnError() *Number

func (*Number) ValidateValue

func (r *Number) ValidateValue(_ context.Context, value any) error

func (*Number) When

func (r *Number) When(v WhenFunc) *Number

func (*Number) WithNotNumberMessage

func (r *Number) WithNotNumberMessage(message string) *Number

func (*Number) WithTooBigMessage

func (r *Number) WithTooBigMessage(message string) *Number

func (*Number) WithTooSmallMessage

func (r *Number) WithTooSmallMessage(message string) *Number

type Numeric

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

func NewNumeric

func NewNumeric(minVal, maxVal float64) *Numeric

func (*Numeric) SkipOnEmpty

func (n *Numeric) SkipOnEmpty() *Numeric

func (*Numeric) SkipOnError

func (n *Numeric) SkipOnError() *Numeric

func (*Numeric) ValidateValue

func (n *Numeric) ValidateValue(_ context.Context, value any) error

func (*Numeric) When

func (n *Numeric) When(v WhenFunc) *Numeric

func (*Numeric) WithNotNumericMessage

func (n *Numeric) WithNotNumericMessage(message string) *Numeric

func (*Numeric) WithTooBigMessage

func (n *Numeric) WithTooBigMessage(message string) *Numeric

func (*Numeric) WithTooSmallMessage

func (n *Numeric) WithTooSmallMessage(message string) *Numeric

type OGRN

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

func NewOGRN

func NewOGRN() *OGRN

func (*OGRN) SkipOnEmpty

func (o *OGRN) SkipOnEmpty() *OGRN

func (*OGRN) SkipOnError

func (o *OGRN) SkipOnError() *OGRN

func (*OGRN) ValidateValue

func (o *OGRN) ValidateValue(_ context.Context, value any) error

func (*OGRN) When

func (o *OGRN) When(v WhenFunc) *OGRN

func (*OGRN) WithOGRNIPMessage

func (o *OGRN) WithOGRNIPMessage(v string) *OGRN

func (*OGRN) WithOGRNMessage

func (o *OGRN) WithOGRNMessage(v string) *OGRN

type OR

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

func NewOR

func NewOR(message string, rules ...Rule) *OR

func (*OR) SkipOnEmpty

func (o *OR) SkipOnEmpty() *OR

func (*OR) SkipOnError

func (o *OR) SkipOnError() *OR

func (*OR) ValidateValue

func (o *OR) ValidateValue(ctx context.Context, value any) error

func (*OR) When

func (o *OR) When(v WhenFunc) *OR

func (*OR) WithMessage

func (o *OR) WithMessage(message string) *OR

type Required

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

func NewRequired

func NewRequired() *Required

func (*Required) SkipOnError

func (r *Required) SkipOnError() *Required

func (*Required) ValidateValue

func (r *Required) ValidateValue(_ context.Context, value any) error

func (*Required) When

func (r *Required) When(v WhenFunc) *Required

func (*Required) WithAllowZeroValue deprecated

func (r *Required) WithAllowZeroValue() *Required

Deprecated: should be removed

func (*Required) WithMessage

func (r *Required) WithMessage(message string) *Required

type Result

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

func NewResult

func NewResult() Result

func (Result) AttributeErrorMessagesIndexedByPath

func (s Result) AttributeErrorMessagesIndexedByPath(attribute string) map[string][]string

func (Result) CommonErrorMessages

func (s Result) CommonErrorMessages() []string

func (Result) Error

func (s Result) Error() string

func (Result) ErrorMessagesIndexedByPath

func (s Result) ErrorMessagesIndexedByPath() map[string][]string

func (Result) Errors

func (s Result) Errors() []*ValidationError

func (Result) IsValid

func (s Result) IsValid() bool

func (Result) WithError

func (s Result) WithError(errs ...*ValidationError) Result

type Rule

type Rule interface {
	ValidateValue(ctx context.Context, value any) error
}

type RuleSet

type RuleSet map[string]Rules

type RuleSkipEmpty

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

type RuleSkipError

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

type RuleWhen

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

type Rules

type Rules []Rule

func (Rules) SkipOnError

func (rs Rules) SkipOnError()

type SQL

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

func NewSQL

func NewSQL() *SQL

func (*SQL) AsWhereClause

func (r *SQL) AsWhereClause() *SQL

func (*SQL) SkipOnEmpty

func (r *SQL) SkipOnEmpty() *SQL

func (*SQL) SkipOnError

func (r *SQL) SkipOnError() *SQL

func (*SQL) ValidateValue

func (r *SQL) ValidateValue(_ context.Context, value any) error

func (*SQL) When

func (r *SQL) When(v WhenFunc) *SQL

func (*SQL) WithMessage

func (r *SQL) WithMessage(message string) *SQL

type StringLength

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

func NewStringLength

func NewStringLength(minLen, maxLen int) *StringLength

func (*StringLength) SkipOnEmpty

func (r *StringLength) SkipOnEmpty() *StringLength

func (*StringLength) SkipOnError

func (r *StringLength) SkipOnError() *StringLength

func (*StringLength) ValidateValue

func (r *StringLength) ValidateValue(_ context.Context, value any) error

func (*StringLength) When

func (r *StringLength) When(v WhenFunc) *StringLength

func (*StringLength) WithMessage

func (r *StringLength) WithMessage(message string) *StringLength

func (*StringLength) WithTooLongMessage

func (r *StringLength) WithTooLongMessage(message string) *StringLength

func (*StringLength) WithTooShortMessage

func (r *StringLength) WithTooShortMessage(message string) *StringLength

type Time

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

func NewTime

func NewTime() *Time

func (*Time) SkipOnEmpty

func (r *Time) SkipOnEmpty() *Time

func (*Time) SkipOnError

func (r *Time) SkipOnError() *Time

func (*Time) ValidateValue

func (r *Time) ValidateValue(ctx context.Context, value any) error

func (*Time) When

func (r *Time) When(v WhenFunc) *Time

func (*Time) WithFormat

func (r *Time) WithFormat(format string) *Time

func (*Time) WithFormatMessage

func (r *Time) WithFormatMessage(message string) *Time

func (*Time) WithMax

func (r *Time) WithMax(maxFunc TimeFunc) *Time

func (*Time) WithMessage

func (r *Time) WithMessage(message string) *Time

func (*Time) WithMin

func (r *Time) WithMin(minFunc TimeFunc) *Time

func (*Time) WithTooBigMessage

func (r *Time) WithTooBigMessage(message string) *Time

func (*Time) WithTooSmallMessage

func (r *Time) WithTooSmallMessage(message string) *Time

type TimeFunc

type TimeFunc func(ctx context.Context) (time.Time, error)

type TranslationCatalog added in v2.10.0

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

func NewTranslationCatalog added in v2.10.0

func NewTranslationCatalog() *TranslationCatalog

func (*TranslationCatalog) Get added in v2.10.0

func (c *TranslationCatalog) Get(lang Language, id string) (string, bool)

func (*TranslationCatalog) Missing added in v2.10.0

func (c *TranslationCatalog) Missing(lang Language) []string

func (*TranslationCatalog) Register added in v2.10.0

func (c *TranslationCatalog) Register(lang Language, messages map[string]string)

type Translator

type Translator interface {
	Translate(
		ctx context.Context,
		id string,
		params map[string]any,
	) string
}
var DefaultTranslator Translator = NewCatalogTranslator(Translations)

type URL

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

func NewURL

func NewURL() *URL

func (*URL) SkipOnEmpty

func (r *URL) SkipOnEmpty() *URL

func (*URL) SkipOnError

func (r *URL) SkipOnError() *URL

func (*URL) ValidateValue

func (r *URL) ValidateValue(_ context.Context, value any) error

func (*URL) When

func (r *URL) When(v WhenFunc) *URL

func (*URL) WithEnableIDN

func (r *URL) WithEnableIDN() *URL

func (*URL) WithMessage

func (r *URL) WithMessage(message string) *URL

func (*URL) WithPattern

func (r *URL) WithPattern(pattern string) *URL

func (*URL) WithValidScheme

func (r *URL) WithValidScheme(scheme ...string) *URL

type UUID

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

func NewUUID

func NewUUID() *UUID

func (*UUID) SkipOnEmpty

func (r *UUID) SkipOnEmpty() *UUID

func (*UUID) SkipOnError

func (r *UUID) SkipOnError() *UUID

func (*UUID) ValidateValue

func (r *UUID) ValidateValue(_ context.Context, value any) error

func (*UUID) When

func (r *UUID) When(v WhenFunc) *UUID

func (*UUID) WithInvalidVersionMessage

func (r *UUID) WithInvalidVersionMessage(message string) *UUID

func (*UUID) WithMessage

func (r *UUID) WithMessage(message string) *UUID

func (*UUID) WithVersion

func (r *UUID) WithVersion(version UUIDVersion) *UUID

type UUIDVersion

type UUIDVersion byte
const (
	UUIDVersionV1 UUIDVersion = 1
	UUIDVersionV3 UUIDVersion = 3
	UUIDVersionV4 UUIDVersion = 4
	UUIDVersionV5 UUIDVersion = 5
	UUIDVersionV6 UUIDVersion = 6
	UUIDVersionV7 UUIDVersion = 7
)

type UniqueValues

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

func NewUniqueValues

func NewUniqueValues() *UniqueValues

func (*UniqueValues) SkipOnEmpty

func (r *UniqueValues) SkipOnEmpty() *UniqueValues

func (*UniqueValues) SkipOnError

func (r *UniqueValues) SkipOnError() *UniqueValues

func (*UniqueValues) ValidateValue

func (r *UniqueValues) ValidateValue(_ context.Context, value any) error

ValidateValue checks that all elements in a slice are unique. For pointer slices ([]*T), elements are dereferenced before comparison so that two distinct pointers with equal values are detected as duplicates.

The element type determines the comparison strategy:

  • Statically comparable types (primitives, fixed-size structs, pointers): O(n) hash map lookup via map[any]struct{}.
  • Everything else (structs with slice/map fields, interface slices): O(n) bucketed FNV-64a hash lookup with reflect.DeepEqual collision fallback — see validateHashKey.

Interface-typed slices ([]any, []io.Reader, ...) deliberately skip the comparable fast path: reflect.Type.Comparable reports true for interface kinds because they are syntactically comparable, but the runtime hash panics on non-comparable dynamic values. Routing them through the bucketed-hash path handles any dynamic type correctly.

func (*UniqueValues) When

func (r *UniqueValues) When(v WhenFunc) *UniqueValues

func (*UniqueValues) WithMessage

func (r *UniqueValues) WithMessage(message string) *UniqueValues

type ValidationError

type ValidationError struct {
	Message   string
	Params    map[string]any
	ValuePath []string
}

func NewValidationError

func NewValidationError(message string) *ValidationError

func (*ValidationError) Error

func (v *ValidationError) Error() string

func (*ValidationError) WithParams

func (v *ValidationError) WithParams(params map[string]any) *ValidationError

func (*ValidationError) WithValuePath

func (v *ValidationError) WithValuePath(valuePath []string) *ValidationError

type WhenFunc

type WhenFunc func(ctx context.Context, value any) bool

Directories

Path Synopsis
*
*
*
*
*

Jump to

Keyboard shortcuts

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