govalid

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 21 Imported by: 0

README

govalid v1 gopher mascot

🐳 govalid

Composable, type-aware validation for Go structs.
Explicit by default. Extensible when you need it.

Go Reference GitHub release Go 1.26 MIT license

Quick start · Rules · Errors · Extensibility · API reference


govalid validates the fields you choose with ordinary Go functions. Rules stay visible in code, compose across data types, and work without a tag language, global registry, or code generation.

err := govalid.New().Validate(
	user,
	govalid.Field("Name", govalid.Required(), govalid.StringMinLength(3)),
	govalid.Field("Age", govalid.IntBetween(18, 130)),
	govalid.Field("Profile.Email", govalid.StringEmail()),
)

Why teams choose govalid

🧩 Composable Reuse rules inside maps, collections, bytes, and conditional flows.
🔎 Explicit Validation is easy to find, review, refactor, and test.
🧠 Type-aware Signed and unsigned integers, derived types, floats, bytes, maps, slices, and arrays are handled deliberately.
🧭 Nested Address fields with paths such as "Profile.Email"; use FieldIfPresent for nullable parents.
🧰 Extensible Build custom Rule functions and custom FieldSource discovery mechanisms.
Reusable A configured Validator can be shared across concurrent calls when callbacks and sources are concurrency-safe.

Install

go get github.com/rickferrdev/govalid@latest

The project is finalizing its v1.0.0 contract. Until the stable tag is published, prereleases may still include breaking cleanup.

Quick start

package main

import (
	"errors"
	"fmt"

	"github.com/rickferrdev/govalid"
)

type Profile struct {
	Email string
}

type User struct {
	Name    string
	Age     uint
	Profile *Profile
	Scores  []int
	Labels  map[string]string
	Payload []byte
}

func main() {
	user := User{
		Name:    "Alice",
		Age:     24,
		Profile: &Profile{Email: "alice@example.com"},
		Scores:  []int{98, 91, 87},
		Labels:  map[string]string{"environment": "production"},
		Payload: []byte(`{"active":true}`),
	}

	err := govalid.New().Validate(
		user,
		govalid.Field("Name", govalid.Required(), govalid.StringMinLength(3)),
		govalid.Field("Age", govalid.IntBetween(18, 130)),
		govalid.FieldIfPresent("Profile.Email", govalid.StringEmail()),
		govalid.Field("Scores", govalid.CollectionEach(govalid.IntBetween(0, 100))),
		govalid.Field("Labels", govalid.MapKeys(govalid.StringLowercase())),
		govalid.Field("Payload", govalid.BytesJSON()),
	)

	var validationErr *govalid.FieldIssueError
	if errors.As(err, &validationErr) {
		for _, issue := range validationErr.RulesIssues {
			fmt.Printf("%s: %s (rule: %s)\n", issue.Path, issue.Message, issue.Rule)
		}
	}
}

Rules

Category What you can validate
String Unicode length, content, case, regex, email, URL, and UUID
Integer Every signed/unsigned variant, comparisons, sets, arithmetic, and domains
Float Comparisons, tolerance, bit width, NaN, infinity, and finiteness
Boolean True, false, and equality
Bytes Length, equality, content, UTF-8, JSON, XML, PEM, Hex, and Base64
Map Keys, values, length, equality, subsets, and nested rules
Collection Content, uniqueness, length, equality, and nested item rules
Universal Required, nil, non-nil, zero, and non-zero values
Conditional When, Unless, context-aware conditions, and Optional

Integer comparisons preserve the complete uint64 range even when signed and unsigned values are mixed. Defined types with supported underlying kinds work as well.

Compose instead of repeating

govalid.Field(
	"Labels",
	govalid.Required(),
	govalid.MapKeys(govalid.StringLowercase()),
	govalid.MapValues(govalid.StringRequired()),
)

govalid.Field(
	"Scores",
	govalid.Optional(
		govalid.CollectionEach(govalid.IntBetween(0, 100)),
	),
)

Context-aware conditions can inspect the selected value and root struct:

govalid.WhenContext(func(ctx govalid.RuleContext) bool {
	return ctx.RootAny().(User).Age >= 18
}, govalid.StringRequired())

Errors you can use

Validation collects every issue by default. errors.As can extract the full *FieldIssueError or its first *Issue.

type Issue struct {
	Path    string
	Value   any
	Rule    string
	Message string
}

Choose the execution flow that fits the boundary you are validating:

govalid.New()                                // collect every issue
govalid.New(govalid.WithStopOnFirstError())  // return after the first issue
govalid.New(govalid.WithPanicOnFirstError()) // panic with *govalid.Issue
govalid.New(govalid.WithSilenceErrors())     // run rules and return nil

Observe failures independently of the return mode:

validator := govalid.New(
	govalid.WithIssueHandler(func(issue govalid.Issue) {
		log.Printf("validation %s: %s", issue.Path, issue.Message)
	}),
)

Large values remain available in Issue.Value, while their formatted error representation is summarized to keep logs manageable.

Built to extend

Custom rules use the same context as built-in rules:

isSlug := govalid.Rule(func(ctx govalid.RuleContext) error {
	value, ok := ctx.ValueAny().(string)
	if !ok || value == "" {
		return errors.New("should be a slug")
	}
	return nil
})

FieldSource separates field discovery from rule execution. A future tag, schema, or generated integration can return ordinary FieldSpec values and reuse the same validator:

type FieldSource interface {
	Fields(structType reflect.Type) ([]govalid.FieldSpec, error)
}

Sources are additive and run before fields passed directly to Validate. Shared sources and issue handlers must be concurrency-safe.

v1 scope

The first stable release focuses on explicit field validation. Built-in struct tags and recursive Struct* rules are intentionally outside the initial v1 scope. The FieldSource boundary keeps those integrations possible later without replacing Validator, Rule, or FieldSpec.

The suite includes external API tests, concurrent reuse tests, and large payload tests with 100,000 collection items, 10,000 map entries, nested matrices, and megabyte-sized byte documents.

Documentation

Development

go test ./...
go vet ./...

License

Released under the MIT License.

Documentation

Overview

Package govalid provides composable, type-aware validation rules for selected fields of Go structs.

Validation is explicit: callers associate field paths with rules through Field and execute them with a Validator. Rules cover strings, booleans, integers, floating-point numbers, bytes, maps, collections, universal value states, and conditional composition. Consumers can also implement custom rules with RuleContext and plug alternate field-declaration mechanisms into Validator with FieldSource.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Condition

type Condition func(context RuleContext) bool

Condition decides whether contextual rules should run.

type FieldIssueError

type FieldIssueError struct {
	RulesIssues []Issue
}

FieldIssueError contains the issues collected during one validation run.

func (*FieldIssueError) As

func (field *FieldIssueError) As(target any) bool

As lets errors.As extract the first individual Issue from a validation error. Extract FieldIssueError itself to inspect every collected issue.

func (*FieldIssueError) Error

func (field *FieldIssueError) Error() string

Error formats every collected validation issue.

type FieldSource

type FieldSource interface {
	Fields(structType reflect.Type) ([]FieldSpec, error)
}

FieldSource discovers field specifications for a struct type. It allows alternate declaration mechanisms, such as a future struct-tag parser, to reuse Validator without changing its execution API.

Implementations used concurrently must be concurrency-safe.

type FieldSourceFunc

type FieldSourceFunc func(structType reflect.Type) ([]FieldSpec, error)

FieldSourceFunc adapts a function to FieldSource.

func (FieldSourceFunc) Fields

func (source FieldSourceFunc) Fields(structType reflect.Type) ([]FieldSpec, error)

Fields discovers field specifications for structType.

type FieldSpec

type FieldSpec struct {
	Path  string
	Rules []Rule
	// contains filtered or unexported fields
}

FieldSpec associates a struct field path with validation rules.

func Field

func Field(path string, rules ...Rule) FieldSpec

Field associates a dot-separated struct field path with validation rules.

func FieldIfPresent

func FieldIfPresent(path string, rules ...Rule) FieldSpec

FieldIfPresent associates rules with a field path but skips them when an intermediate pointer or interface in that path is nil. The selected field itself is still validated when its parent path exists.

type Issue

type Issue struct {
	Path    string
	Value   any
	Rule    string
	Message string
}

Issue describes one failed validation rule.

func (*Issue) Error

func (issue *Issue) Error() string

Error formats the failed rule, path, rejected value, and message.

type Option

type Option func(opts *options)

Option configures a Validator during construction.

func WithFieldSources

func WithFieldSources(sources ...FieldSource) Option

WithFieldSources registers field-discovery extensions that run before the explicit FieldSpec values passed to Validate. Sources are copied during construction and must be concurrency-safe when the Validator is shared.

func WithIssueHandler

func WithIssueHandler(handler func(Issue)) Option

WithIssueHandler registers a callback invoked once for every failed rule. The handler runs before stop, panic, and silence behavior is applied. A handler used by concurrent validations must itself be concurrency-safe.

func WithPanicOnFirstError

func WithPanicOnFirstError() Option

WithPanicOnFirstError makes validation panic with an Issue on the first failed rule.

func WithSilenceErrors

func WithSilenceErrors() Option

WithSilenceErrors makes validation return nil after running applicable rules. Combine it with WithIssueHandler to observe failures.

func WithStopOnFirstError

func WithStopOnFirstError() Option

WithStopOnFirstError makes validation return after the first failed rule.

type Rule

type Rule func(context RuleContext) error

Rule validates the field described by a RuleContext.

func BoolEqual

func BoolEqual(expect bool) Rule

BoolEqual returns a boolean validation rule for equal.

func BoolFalse

func BoolFalse() Rule

BoolFalse returns a boolean validation rule for false.

func BoolTrue

func BoolTrue() Rule

BoolTrue returns a boolean validation rule for true.

func Bytes

func Bytes() Rule

Bytes requires a byte slice or byte array, including defined byte types.

func BytesASCII

func BytesASCII() Rule

BytesASCII returns a byte-sequence validation rule for ascii.

func BytesAllZero

func BytesAllZero() Rule

BytesAllZero returns a byte-sequence validation rule for all zero.

func BytesAt

func BytesAt(index int, rules ...Rule) Rule

BytesAt returns a byte-sequence validation rule for at.

func BytesAtIfPresent

func BytesAtIfPresent(index int, rules ...Rule) Rule

BytesAtIfPresent returns a byte-sequence validation rule for at if present.

func BytesBase64

func BytesBase64() Rule

BytesBase64 returns a byte-sequence validation rule for base64.

func BytesBase64URL

func BytesBase64URL() Rule

BytesBase64URL returns a byte-sequence validation rule for base64url.

func BytesBetween

func BytesBetween(minimum, maximum []byte) Rule

BytesBetween returns a byte-sequence validation rule for between.

func BytesConstantTimeEqual

func BytesConstantTimeEqual(expected []byte) Rule

BytesConstantTimeEqual returns a byte-sequence validation rule for constant time equal.

func BytesContains

func BytesContains(expected []byte) Rule

BytesContains returns a byte-sequence validation rule for contains.

func BytesContainsAll

func BytesContainsAll(expected ...[]byte) Rule

BytesContainsAll returns a byte-sequence validation rule for contains all.

func BytesContainsAny

func BytesContainsAny(expected ...[]byte) Rule

BytesContainsAny returns a byte-sequence validation rule for contains any.

func BytesEach

func BytesEach(rules ...Rule) Rule

BytesEach returns a byte-sequence validation rule for each.

func BytesEmpty

func BytesEmpty() Rule

BytesEmpty returns a byte-sequence validation rule for empty.

func BytesEqual

func BytesEqual(expected []byte) Rule

BytesEqual returns a byte-sequence validation rule for equal.

func BytesGreaterThan

func BytesGreaterThan(expected []byte) Rule

BytesGreaterThan returns a byte-sequence validation rule for greater than.

func BytesGreaterThanOrEqual

func BytesGreaterThanOrEqual(expected []byte) Rule

BytesGreaterThanOrEqual returns a byte-sequence validation rule for greater than or equal.

func BytesHasPrefix

func BytesHasPrefix(prefix []byte) Rule

BytesHasPrefix returns a byte-sequence validation rule for has prefix.

func BytesHasSuffix

func BytesHasSuffix(suffix []byte) Rule

BytesHasSuffix returns a byte-sequence validation rule for has suffix.

func BytesHasZero

func BytesHasZero() Rule

BytesHasZero returns a byte-sequence validation rule for has zero.

func BytesHex

func BytesHex() Rule

BytesHex returns a byte-sequence validation rule for hex.

func BytesJSON

func BytesJSON() Rule

BytesJSON returns a byte-sequence validation rule for json.

func BytesLength

func BytesLength(expect int) Rule

BytesLength returns a byte-sequence validation rule for length.

func BytesLengthBetween

func BytesLengthBetween(minimum, maximum int) Rule

BytesLengthBetween returns a byte-sequence validation rule for length between.

func BytesLengthNotBetween

func BytesLengthNotBetween(minimum, maximum int) Rule

BytesLengthNotBetween returns a byte-sequence validation rule for length not between.

func BytesLessThan

func BytesLessThan(expected []byte) Rule

BytesLessThan returns a byte-sequence validation rule for less than.

func BytesLessThanOrEqual

func BytesLessThanOrEqual(expected []byte) Rule

BytesLessThanOrEqual returns a byte-sequence validation rule for less than or equal.

func BytesMaxLength

func BytesMaxLength(expect int) Rule

BytesMaxLength returns a byte-sequence validation rule for max length.

func BytesMinLength

func BytesMinLength(expect int) Rule

BytesMinLength returns a byte-sequence validation rule for min length.

func BytesNil

func BytesNil() Rule

BytesNil returns a byte-sequence validation rule for nil.

func BytesNoZero

func BytesNoZero() Rule

BytesNoZero returns a byte-sequence validation rule for no zero.

func BytesNoneOf

func BytesNoneOf(unexpected ...[]byte) Rule

BytesNoneOf returns a byte-sequence validation rule for none of.

func BytesNotAllZero

func BytesNotAllZero() Rule

BytesNotAllZero returns a byte-sequence validation rule for not all zero.

func BytesNotContains

func BytesNotContains(unexpected []byte) Rule

BytesNotContains returns a byte-sequence validation rule for not contains.

func BytesNotEmpty

func BytesNotEmpty() Rule

BytesNotEmpty returns a byte-sequence validation rule for not empty.

func BytesNotEqual

func BytesNotEqual(unexpected []byte) Rule

BytesNotEqual returns a byte-sequence validation rule for not equal.

func BytesNotHasPrefix

func BytesNotHasPrefix(prefix []byte) Rule

BytesNotHasPrefix returns a byte-sequence validation rule for not has prefix.

func BytesNotHasSuffix

func BytesNotHasSuffix(suffix []byte) Rule

BytesNotHasSuffix returns a byte-sequence validation rule for not has suffix.

func BytesNotNil

func BytesNotNil() Rule

BytesNotNil returns a byte-sequence validation rule for not nil.

func BytesNotUTF8

func BytesNotUTF8() Rule

BytesNotUTF8 returns a byte-sequence validation rule for not utf8.

func BytesOneOf

func BytesOneOf(expected ...[]byte) Rule

BytesOneOf returns a byte-sequence validation rule for one of.

func BytesPEM

func BytesPEM() Rule

BytesPEM returns a byte-sequence validation rule for pem.

func BytesPrintableASCII

func BytesPrintableASCII() Rule

BytesPrintableASCII returns a byte-sequence validation rule for printable ascii.

func BytesUTF8

func BytesUTF8() Rule

BytesUTF8 returns a byte-sequence validation rule for utf8.

func BytesUnique

func BytesUnique() Rule

BytesUnique returns a byte-sequence validation rule for unique.

func BytesXML

func BytesXML() Rule

BytesXML returns a byte-sequence validation rule for xml.

func Collection

func Collection() Rule

Collection requires a slice or array value.

func CollectionAny

func CollectionAny(rules ...Rule) Rule

CollectionAny returns a collection validation rule for any.

func CollectionContains

func CollectionContains[T any](expected T) Rule

CollectionContains returns a collection validation rule for contains.

func CollectionContainsAll

func CollectionContainsAll[T any](expected ...T) Rule

CollectionContainsAll returns a collection validation rule for contains all.

func CollectionContainsAny

func CollectionContainsAny[T any](expected ...T) Rule

CollectionContainsAny returns a collection validation rule for contains any.

func CollectionEach

func CollectionEach(rules ...Rule) Rule

CollectionEach returns a collection validation rule for each.

func CollectionEmpty

func CollectionEmpty() Rule

CollectionEmpty returns a collection validation rule for empty.

func CollectionEqual

func CollectionEqual[T any](expected T) Rule

CollectionEqual returns a collection validation rule for equal.

func CollectionHasNonZeroItem

func CollectionHasNonZeroItem() Rule

CollectionHasNonZeroItem returns a collection validation rule for has non zero item.

func CollectionItemAt

func CollectionItemAt(index int, rules ...Rule) Rule

CollectionItemAt returns a collection validation rule for item at.

func CollectionItemAtIfPresent

func CollectionItemAtIfPresent(index int, rules ...Rule) Rule

CollectionItemAtIfPresent returns a collection validation rule for item at if present.

func CollectionLength

func CollectionLength(expect int) Rule

CollectionLength returns a collection validation rule for length.

func CollectionLengthBetween

func CollectionLengthBetween(minimum, maximum int) Rule

CollectionLengthBetween returns a collection validation rule for length between.

func CollectionLengthNotBetween

func CollectionLengthNotBetween(minimum, maximum int) Rule

CollectionLengthNotBetween returns a collection validation rule for length not between.

func CollectionMaxLength

func CollectionMaxLength(expect int) Rule

CollectionMaxLength returns a collection validation rule for max length.

func CollectionMinLength

func CollectionMinLength(expect int) Rule

CollectionMinLength returns a collection validation rule for min length.

func CollectionNil

func CollectionNil() Rule

CollectionNil returns a collection validation rule for nil.

func CollectionNoNilItems

func CollectionNoNilItems() Rule

CollectionNoNilItems returns a collection validation rule for no nil items.

func CollectionNoZeroItems

func CollectionNoZeroItems() Rule

CollectionNoZeroItems returns a collection validation rule for no zero items.

func CollectionNone

func CollectionNone(rules ...Rule) Rule

CollectionNone returns a collection validation rule for none.

func CollectionNotContains

func CollectionNotContains[T any](unexpected T) Rule

CollectionNotContains returns a collection validation rule for not contains.

func CollectionNotEmpty

func CollectionNotEmpty() Rule

CollectionNotEmpty returns a collection validation rule for not empty.

func CollectionNotEqual

func CollectionNotEqual[T any](unexpected T) Rule

CollectionNotEqual returns a collection validation rule for not equal.

func CollectionNotNil

func CollectionNotNil() Rule

CollectionNotNil returns a collection validation rule for not nil.

func CollectionUnique

func CollectionUnique() Rule

CollectionUnique returns a collection validation rule for unique.

func FloatBetween

func FloatBetween[Min floating, Max floating](minimum Min, maximum Max) Rule

FloatBetween returns a floating-point validation rule for between.

func FloatBits

func FloatBits(bits int) Rule

FloatBits returns a floating-point validation rule for bits.

func FloatEqual

func FloatEqual[T floating](expect T) Rule

FloatEqual returns a floating-point validation rule for equal.

func FloatEqualWithin

func FloatEqualWithin[T floating](expect T, tolerance float64) Rule

FloatEqualWithin returns a floating-point validation rule for equal within.

func FloatFinite

func FloatFinite() Rule

FloatFinite returns a floating-point validation rule for finite.

func FloatGreaterThan

func FloatGreaterThan[T floating](expect T) Rule

FloatGreaterThan returns a floating-point validation rule for greater than.

func FloatGreaterThanOrEqual

func FloatGreaterThanOrEqual[T floating](expect T) Rule

FloatGreaterThanOrEqual returns a floating-point validation rule for greater than or equal.

func FloatInfinite

func FloatInfinite() Rule

FloatInfinite returns a floating-point validation rule for infinite.

func FloatIs32

func FloatIs32() Rule

FloatIs32 returns a floating-point validation rule for is32.

func FloatIs64

func FloatIs64() Rule

FloatIs64 returns a floating-point validation rule for is64.

func FloatLessThan

func FloatLessThan[T floating](expect T) Rule

FloatLessThan returns a floating-point validation rule for less than.

func FloatLessThanOrEqual

func FloatLessThanOrEqual[T floating](expect T) Rule

FloatLessThanOrEqual returns a floating-point validation rule for less than or equal.

func FloatMax

func FloatMax[T floating](expect T) Rule

FloatMax returns a floating-point validation rule for max.

func FloatMin

func FloatMin[T floating](expect T) Rule

FloatMin returns a floating-point validation rule for min.

func FloatNaN

func FloatNaN() Rule

FloatNaN returns a floating-point validation rule for na n.

func FloatNegative

func FloatNegative() Rule

FloatNegative returns a floating-point validation rule for negative.

func FloatNegativeInfinite

func FloatNegativeInfinite() Rule

FloatNegativeInfinite returns a floating-point validation rule for negative infinite.

func FloatNonNegative

func FloatNonNegative() Rule

FloatNonNegative returns a floating-point validation rule for non negative.

func FloatNonPositive

func FloatNonPositive() Rule

FloatNonPositive returns a floating-point validation rule for non positive.

func FloatNonZero

func FloatNonZero() Rule

FloatNonZero returns a floating-point validation rule for non zero.

func FloatNotBetween

func FloatNotBetween[Min floating, Max floating](minimum Min, maximum Max) Rule

FloatNotBetween returns a floating-point validation rule for not between.

func FloatNotEqual

func FloatNotEqual[T floating](expect T) Rule

FloatNotEqual returns a floating-point validation rule for not equal.

func FloatNotFinite

func FloatNotFinite() Rule

FloatNotFinite returns a floating-point validation rule for not finite.

func FloatNotInfinite

func FloatNotInfinite() Rule

FloatNotInfinite returns a floating-point validation rule for not infinite.

func FloatNotNaN

func FloatNotNaN() Rule

FloatNotNaN returns a floating-point validation rule for not na n.

func FloatPositive

func FloatPositive() Rule

FloatPositive returns a floating-point validation rule for positive.

func FloatPositiveInfinite

func FloatPositiveInfinite() Rule

FloatPositiveInfinite returns a floating-point validation rule for positive infinite.

func FloatZero

func FloatZero() Rule

FloatZero returns a floating-point validation rule for zero.

func IntBetween

func IntBetween[Min integer, Max integer](minimum Min, maximum Max) Rule

IntBetween returns an integer validation rule for between.

func IntCompound

func IntCompound() Rule

IntCompound returns an integer validation rule for compound.

func IntDivisibleBy

func IntDivisibleBy[T integer](n T) Rule

IntDivisibleBy returns an integer validation rule for divisible by.

func IntEqual

func IntEqual[T integer](expect T) Rule

IntEqual returns an integer validation rule for equal.

func IntEven

func IntEven() Rule

IntEven returns an integer validation rule for even.

func IntGreaterThan

func IntGreaterThan[T integer](expect T) Rule

IntGreaterThan returns an integer validation rule for greater than.

func IntGreaterThanOrEqual

func IntGreaterThanOrEqual[T integer](expect T) Rule

IntGreaterThanOrEqual returns an integer validation rule for greater than or equal.

func IntHTTPStatus

func IntHTTPStatus() Rule

IntHTTPStatus returns an integer validation rule for http status.

func IntLessThan

func IntLessThan[T integer](expect T) Rule

IntLessThan returns an integer validation rule for less than.

func IntLessThanOrEqual

func IntLessThanOrEqual[T integer](expect T) Rule

IntLessThanOrEqual returns an integer validation rule for less than or equal.

func IntMax

func IntMax[T integer](expect T) Rule

IntMax returns an integer validation rule for max.

func IntMin

func IntMin[T integer](expect T) Rule

IntMin returns an integer validation rule for min.

func IntMultipleOf

func IntMultipleOf[T integer](n T) Rule

IntMultipleOf returns an integer validation rule for multiple of.

func IntNegative

func IntNegative() Rule

IntNegative returns an integer validation rule for negative.

func IntNonNegative

func IntNonNegative() Rule

IntNonNegative returns an integer validation rule for non negative.

func IntNonPositive

func IntNonPositive() Rule

IntNonPositive returns an integer validation rule for non positive.

func IntNonZero

func IntNonZero() Rule

IntNonZero returns an integer validation rule for non zero.

func IntNoneOf

func IntNoneOf[T integer](restricted ...T) Rule

IntNoneOf returns an integer validation rule for none of.

func IntNotBetween

func IntNotBetween[Min integer, Max integer](minimum Min, maximum Max) Rule

IntNotBetween returns an integer validation rule for not between.

func IntNotEqual

func IntNotEqual[T integer](expect T) Rule

IntNotEqual returns an integer validation rule for not equal.

func IntOdd

func IntOdd() Rule

IntOdd returns an integer validation rule for odd.

func IntOneOf

func IntOneOf[T integer](allowed ...T) Rule

IntOneOf returns an integer validation rule for one of.

func IntPercentage

func IntPercentage() Rule

IntPercentage returns an integer validation rule for percentage.

func IntPerfectSquare

func IntPerfectSquare() Rule

IntPerfectSquare returns an integer validation rule for perfect square.

func IntPort

func IntPort() Rule

IntPort returns an integer validation rule for port.

func IntPositive

func IntPositive() Rule

IntPositive returns an integer validation rule for positive.

func IntPowerOfTwo

func IntPowerOfTwo() Rule

IntPowerOfTwo returns an integer validation rule for power of two.

func IntPrime

func IntPrime() Rule

IntPrime returns an integer validation rule for prime.

func IntZero

func IntZero() Rule

IntZero returns an integer validation rule for zero.

func Map

func Map() Rule

Map requires a map value.

func MapAllowedKeys

func MapAllowedKeys[K comparable](allowed ...K) Rule

MapAllowedKeys returns a map validation rule for allowed keys.

func MapContainsAllValues

func MapContainsAllValues[V any](expected ...V) Rule

MapContainsAllValues returns a map validation rule for contains all values.

func MapContainsAnyValue

func MapContainsAnyValue[V any](expected ...V) Rule

MapContainsAnyValue returns a map validation rule for contains any value.

func MapContainsValue

func MapContainsValue[V any](expected V) Rule

MapContainsValue returns a map validation rule for contains value.

func MapEmpty

func MapEmpty() Rule

MapEmpty returns a map validation rule for empty.

func MapEqual

func MapEqual[M ~map[K]V, K comparable, V any](expected M) Rule

MapEqual returns a map validation rule for equal.

func MapHasAllKeys

func MapHasAllKeys[K comparable](expected ...K) Rule

MapHasAllKeys returns a map validation rule for has all keys.

func MapHasAnyKey

func MapHasAnyKey[K comparable](expected ...K) Rule

MapHasAnyKey returns a map validation rule for has any key.

func MapHasExactKeys

func MapHasExactKeys[K comparable](expected ...K) Rule

MapHasExactKeys returns a map validation rule for has exact keys.

func MapHasKey

func MapHasKey[K comparable](expected K) Rule

MapHasKey returns a map validation rule for has key.

func MapHasNonZeroValue

func MapHasNonZeroValue() Rule

MapHasNonZeroValue returns a map validation rule for has non zero value.

func MapHasNoneOfKeys

func MapHasNoneOfKeys[K comparable](unexpected ...K) Rule

MapHasNoneOfKeys returns a map validation rule for has none of keys.

func MapKeys

func MapKeys(rules ...Rule) Rule

MapKeys returns a map validation rule for keys.

func MapLength

func MapLength(expect int) Rule

MapLength returns a map validation rule for length.

func MapLengthBetween

func MapLengthBetween(minimum, maximum int) Rule

MapLengthBetween returns a map validation rule for length between.

func MapLengthNotBetween

func MapLengthNotBetween(minimum, maximum int) Rule

MapLengthNotBetween returns a map validation rule for length not between.

func MapMaxLength

func MapMaxLength(expect int) Rule

MapMaxLength returns a map validation rule for max length.

func MapMinLength

func MapMinLength(expect int) Rule

MapMinLength returns a map validation rule for min length.

func MapNil

func MapNil() Rule

MapNil returns a map validation rule for nil.

func MapNoNilValues

func MapNoNilValues() Rule

MapNoNilValues returns a map validation rule for no nil values.

func MapNoZeroValues

func MapNoZeroValues() Rule

MapNoZeroValues returns a map validation rule for no zero values.

func MapNotContainsValue

func MapNotContainsValue[V any](unexpected V) Rule

MapNotContainsValue returns a map validation rule for not contains value.

func MapNotEmpty

func MapNotEmpty() Rule

MapNotEmpty returns a map validation rule for not empty.

func MapNotEqual

func MapNotEqual[M ~map[K]V, K comparable, V any](unexpected M) Rule

MapNotEqual returns a map validation rule for not equal.

func MapNotHasKey

func MapNotHasKey[K comparable](unexpected K) Rule

MapNotHasKey returns a map validation rule for not has key.

func MapNotNil

func MapNotNil() Rule

MapNotNil returns a map validation rule for not nil.

func MapSubsetOf

func MapSubsetOf[M ~map[K]V, K comparable, V any](expected M) Rule

MapSubsetOf returns a map validation rule for subset of.

func MapSupersetOf

func MapSupersetOf[M ~map[K]V, K comparable, V any](expected M) Rule

MapSupersetOf returns a map validation rule for superset of.

func MapValueAt

func MapValueAt[K comparable](key K, rules ...Rule) Rule

MapValueAt returns a map validation rule for value at.

func MapValueAtIfPresent

func MapValueAtIfPresent[K comparable](key K, rules ...Rule) Rule

MapValueAtIfPresent returns a map validation rule for value at if present.

func MapValues

func MapValues(rules ...Rule) Rule

MapValues returns a map validation rule for values.

func Nil

func Nil() Rule

Nil requires a nil-capable value to be nil.

func NotNil

func NotNil() Rule

NotNil rejects nil values. Values whose kinds cannot be nil always pass.

func NotZero

func NotZero() Rule

NotZero rejects the zero value of the field type.

func Optional

func Optional(rules ...Rule) Rule

Optional skips rules for nil and empty values. Scalar values, including 0 and false, are not considered absent and are validated normally.

func Required

func Required() Rule

Required rejects nil values and empty strings, arrays, slices, and maps. Scalar zero values such as 0 and false are considered present; combine it with NotZero when a non-zero scalar is required.

func StringASCII

func StringASCII() Rule

StringASCII returns a string validation rule for ascii.

func StringAlpha

func StringAlpha() Rule

StringAlpha returns a string validation rule for alpha.

func StringAlphaNumeric

func StringAlphaNumeric() Rule

StringAlphaNumeric returns a string validation rule for alpha numeric.

func StringContains

func StringContains(expect string) Rule

StringContains returns a string validation rule for contains.

func StringContainsFold

func StringContainsFold(expect string) Rule

StringContainsFold returns a string validation rule for contains fold.

func StringEmail

func StringEmail() Rule

StringEmail returns a string validation rule for email.

func StringEndsWith

func StringEndsWith(expect string) Rule

StringEndsWith returns a string validation rule for ends with.

func StringEndsWithFold

func StringEndsWithFold(expect string) Rule

StringEndsWithFold returns a string validation rule for ends with fold.

func StringLength

func StringLength(expect int) Rule

StringLength returns a string validation rule for length.

func StringLowercase

func StringLowercase() Rule

StringLowercase returns a string validation rule for lowercase.

func StringMaxLength

func StringMaxLength(expect int) Rule

StringMaxLength returns a string validation rule for max length.

func StringMinLength

func StringMinLength(expect int) Rule

StringMinLength returns a string validation rule for min length.

func StringNotContains

func StringNotContains(expect string) Rule

StringNotContains returns a string validation rule for not contains.

func StringNotContainsFold

func StringNotContainsFold(expect string) Rule

StringNotContainsFold returns a string validation rule for not contains fold.

func StringNotOneOf

func StringNotOneOf(unexpected ...string) Rule

StringNotOneOf returns a string validation rule for not one of.

func StringNumeric

func StringNumeric() Rule

StringNumeric returns a string validation rule for numeric.

func StringOneOf

func StringOneOf(expected ...string) Rule

StringOneOf returns a string validation rule for one of.

func StringRegex

func StringRegex(expression regexp.Regexp) Rule

StringRegex returns a string validation rule for regex.

func StringRequired

func StringRequired() Rule

StringRequired returns a string validation rule for required.

func StringStartsWith

func StringStartsWith(expect string) Rule

StringStartsWith returns a string validation rule for starts with.

func StringStartsWithFold

func StringStartsWithFold(expect string) Rule

StringStartsWithFold returns a string validation rule for starts with fold.

func StringTrimmed

func StringTrimmed() Rule

StringTrimmed returns a string validation rule for trimmed.

func StringURL

func StringURL() Rule

StringURL returns a string validation rule for url.

func StringUUID

func StringUUID() Rule

StringUUID returns a string validation rule for uuid.

func StringUppercase

func StringUppercase() Rule

StringUppercase returns a string validation rule for uppercase.

func Unless

func Unless(condition bool, rules ...Rule) Rule

Unless applies rules only when condition is false.

func UnlessContext

func UnlessContext(condition Condition, rules ...Rule) Rule

UnlessContext applies rules when condition rejects the current RuleContext.

func When

func When(condition bool, rules ...Rule) Rule

When applies rules only when condition is true.

func WhenContext

func WhenContext(condition Condition, rules ...Rule) Rule

WhenContext applies rules when condition accepts the current RuleContext.

func Zero

func Zero() Rule

Zero requires the field to be the zero value of its type.

type RuleContext

type RuleContext struct {
	Root  reflect.Value
	Path  string
	Value reflect.Value
}

RuleContext contains the values available to a validation rule.

Root is the validated struct, Value is the selected field, and Path is the field path passed to Field.

func (RuleContext) RootAny

func (context RuleContext) RootAny() any

RootAny returns the validated struct as an interface value. It returns nil when the root is invalid or cannot be interfaced.

func (RuleContext) ValueAny

func (context RuleContext) ValueAny() any

ValueAny returns the selected field as an interface value. It returns nil when the value is invalid or cannot be interfaced.

type Validator

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

Validator validates selected fields of Go structs. A Validator is safe for concurrent use after construction when its issue handler, if any, is also concurrency-safe.

func New

func New(options ...Option) *Validator

New creates a Validator configured with options.

func (*Validator) Validate

func (sttr *Validator) Validate(data any, fields ...FieldSpec) error

Validate applies field specifications to a struct or pointer to a struct. It returns nil when every rule passes or when errors are explicitly silenced.

Jump to

Keyboard shortcuts

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