check

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 13 Imported by: 0

README

check

CI Status codecov Go Report Card CodeQL Go Reference License Go Version Release

Fluent validation for Go with struct tag verification.

Usage

type User struct {
    Email    string  `json:"email" validate:"required,email"`
    Password string  `json:"password" validate:"required,min=8"`
    Name     *string `json:"name" validate:"omitempty,max=100"`
    Age      int     `json:"age" validate:"min=13,max=120"`
}

func (u *User) Validate() error {
    return check.Check[User](
        check.Str(u.Email, "email").Required().Email().MaxLen(255).V(),
        check.Str(u.Password, "password").Required().MinLen(8).V(),
        check.OptStr(u.Name, "name").MaxLen(100).V(),
        check.Num(u.Age, "age").Between(13, 120).V(),
    ).Err()
}

Check[T] validates your fields and verifies that every field with a validate tag was actually checked. Forget a field? You'll know:

password: tagged but not validated (validate: required,min=8)

No magic, no reflection at validation time—just functions that return validation results.

r := user.Validate()
if r.Err() != nil {
    fmt.Println(r.Err())
    // email: must be a valid email address; age: must be between 13 and 120

    for _, fe := range check.GetFieldErrors(r) {
        fmt.Printf("%s: %s\n", fe.Field, fe.Message)
    }
    // email: must be a valid email address
    // age: must be between 13 and 120
}

Validation logic lives where you can see it, test it, and refactor it.

Install

go get github.com/zoobz-io/check

Requires Go 1.24+.

Fluent Builders

Chain validators naturally:

// Strings
check.Str(email, "email").Required().Email().MaxLen(255).V()

// Optional strings (nil skips validation)
check.OptStr(name, "name").MaxLen(100).V()

// Numbers
check.Num(age, "age").Between(13, 120).V()

// Integers (adds Even, Odd, MultipleOf)
check.Int(count, "count").Positive().Even().V()

// Slices with auto-generated field names
check.StrSlice(tags, "tags").NotEmpty().MaxItems(10).Each(func(b *check.StrBuilder) {
    b.MaxLen(50)  // Validates tags[0], tags[1], etc.
}).V()

Conditional validation with .When():

check.Str(password, "password").
    Required().
    When(requireStrong, func(b *check.StrBuilder) {
        b.MinLen(12).Match(complexityRegex)
    }).V()

Direct Functions

Use validators directly when you don't need the fluent API:

check.All(
    check.Required(email, "email"),
    check.Email(email, "email"),
    check.Between(age, 13, 120, "age"),
)

Capabilities

Category Builders Functions
Strings Str, OptStr Required, MinLen, MaxLen, Match, Prefix, Suffix, OneOf, Alpha, Slug, etc.
Numbers Num, OptNum, Int, OptInt Min, Max, Between, Positive, Negative, NonZero, MultipleOf, Percentage
Slices Slice, OptSlice, StrSlice, OptStrSlice NotEmpty, MinItems, Unique, ContainsAll, Each, AllSatisfy, Subset
Formats (via Str methods) Email, URL, UUID, IP, CIDR, Semver, E164, CreditCard, JSON, Base64
Comparison Equal, NotEqual, GreaterThan, LessThan, EqualField, GreaterThanField
Maps NotEmptyMap, HasKey, HasKeys, OnlyKeys, EachKey, EachMapValue, UniqueValues
Pointers NotNil, Nil, NilOr, RequiredPtr, DefaultOr, Deref
Time Before, After, InPast, InFuture, BetweenTime, WithinDuration, NotWeekend
Aggregation All (collect all errors), First (fail-fast), Merge, Check[T] (with tag verification)

Validation Tracking

Check tracks which validators were applied to which fields, enabling downstream verification of validation coverage.

r := check.All(
    check.Required(email, "email"),
    check.Email(email, "email"),
    check.Between(age, 13, 120, "age"),
)

// Check if specific validators ran
r.HasValidator("email", "required") // true
r.HasValidator("email", "email")    // true
r.HasValidator("age", "min")        // true (Between reports min and max)
r.HasValidator("age", "max")        // true

// Get all validators for a field
r.ValidatorsFor("email") // []string{"required", "email"}

// Get all validated fields
r.Fields() // []string{"email", "age"}

// Get full tracking map
r.Applied() // map[string][]string{"email": {"required", "email"}, "age": {"min", "max"}}

This enables tools to verify that declared validation rules match actual runtime validation.

Why check?

  • Fluent API — chain validators, reduce boilerplate
  • Tag verificationCheck[T] catches forgotten fields at runtime
  • Zero reflection — validation is function calls, fully visible and debuggable
  • Type-safe genericsMin[T], Between[T], Each[T] catch type errors at compile time
  • ComposableAll() collects errors, First() fails fast, nest them freely
  • Field-aware errors — every error knows which field failed and why
  • Validation tracking — verify which validators ran on which fields

Validation as Code

Check enables a pattern: validation logic as visible, testable code.

Your validation rules live in methods alongside your types. They're testable, refactorable, and readable. No tag DSL to learn, no reflection overhead, no magic.

// Conditional validation — just Go code
func (o Order) Validate() error {
    validations := []*check.Validation{
        check.Str(o.ID, "id").Required().UUID().V(),
        check.Num(o.Total, "total").Positive().V(),
    }

    if o.ShipmentType == "express" {
        validations = append(validations,
            check.Str(o.ExpressCode, "express_code").Required().V(),
        )
    }

    return check.All(validations...).Err()
}

// Cross-field validation — just compare values
func (r DateRange) Validate() error {
    return check.All(
        check.NotZeroTime(r.Start, "start"),
        check.NotZeroTime(r.End, "end"),
        check.GreaterThanField(r.End, r.Start, "end", "start"),
    ).Err()
}

// Slice element validation — auto-generated field names
func (c Cart) Validate() error {
    return check.All(
        check.StrSlice(c.ItemIDs, "items").NotEmpty().Each(func(b *check.StrBuilder) {
            b.Required().UUID()
        }).V(),
    ).Err()
}

The compiler checks your validation logic. Your IDE can navigate to it. Your tests can exercise it directly.

Documentation

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT License — see LICENSE for details.

Documentation

Overview

Package check provides zero-reflection validation primitives for Go.

Overview

check offers explicit validation functions with no struct tags or reflection. Validators are composable via All for collecting multiple errors, or First for fail-fast behavior.

Basic Usage

func (r *Request) Validate() error {
    return check.All(
        check.Required(r.Email, "email"),
        check.Email(r.Email, "email"),
        check.MinLen(r.Password, 8, "password"),
    )
}

Error Handling

All validators return *FieldError on failure, which includes the field name and a descriptive message. The All function collects errors into an Errors slice, while First returns only the first error encountered.

err := check.All(
    check.Required(name, "name"),
    check.Email(email, "email"),
)
if err != nil {
    for _, fe := range check.GetFieldErrors(err) {
        fmt.Printf("%s: %s\n", fe.Field, fe.Message)
    }
}

Validator Categories

String validators: Required, MinLen, MaxLen, Len, Match, OneOf, Alpha, AlphaNumeric, Slug, Identifier, and more.

Format validators: Email, URL, UUID, IP, IPv4, IPv6, CIDR, MAC, HexColor, JSON, Semver, E164, CreditCard, and more.

Numeric validators: Min, Max, Between, Positive, Negative, NonZero, MultipleOf, Even, Odd, and more.

Slice validators: NotEmpty, MinItems, MaxItems, Unique, Each, ContainsAll, ContainsAny, Subset, and more.

Map validators: NotEmptyMap, HasKey, HasKeys, OnlyKeys, UniqueValues, and more.

Pointer validators: NotNil, NilOr, RequiredPtr, Deref, and more.

Time validators: Before, After, BetweenTime, WithinDuration, SameDay, Weekday, NotWeekend, and more.

Comparison validators: Equal, NotEqual, EqualField, GreaterThanField, and more.

Optional Field Validation

Use NilOr to validate pointer fields only when present:

check.NilOr(r.MiddleName, func(v string) error {
    return check.MaxLen(v, 100, "middle_name")
})

Slice Element Validation

Use Each to validate every element in a slice:

check.Each(r.Tags, func(tag string, i int) error {
    return check.All(
        check.Required(tag, fmt.Sprintf("tags[%d]", i)),
        check.MaxLen(tag, 50, fmt.Sprintf("tags[%d]", i)),
    )
}, "tags")

Package check provides zero-reflection validation primitives for Go. Explicit validation functions, no struct tags, fully composable.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Deref

func Deref[T any](v *T) T

Deref safely dereferences a pointer, returning the zero value if nil.

func DerefOr

func DerefOr[T any](v *T, defaultVal T) T

DerefOr safely dereferences a pointer, returning the default if nil.

func FieldNames

func FieldNames(r *Result) []string

FieldNames returns all field names that have errors.

func HasErrors

func HasErrors(r *Result) bool

HasErrors checks if a Result has any errors. Convenience function for conditional validation flows.

func HasField

func HasField(r *Result, field string) bool

HasField checks if the Result contains a validation error for the given field.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to the given value.

Types

type Errors

type Errors []error

Errors is a collection of validation errors.

func (Errors) Error

func (e Errors) Error() string

func (Errors) Unwrap

func (e Errors) Unwrap() []error

Unwrap returns the underlying errors for use with errors.Is/As.

type FieldError

type FieldError struct {
	Field   string
	Message string
}

FieldError represents a validation error for a specific field.

func GetFieldErrors

func GetFieldErrors(r *Result) []*FieldError

GetFieldErrors extracts all FieldError values from a Result.

func (*FieldError) Error

func (e *FieldError) Error() string

type Float

type Float interface {
	~float32 | ~float64
}

Float is a constraint for floating-point types.

type IntBuilder

type IntBuilder[T Integer] struct {
	// contains filtered or unexported fields
}

IntBuilder provides fluent validation for integer values.

func Int

func Int[T Integer](v T, field string) *IntBuilder[T]

Int creates a new integer validation builder.

func (*IntBuilder[T]) Between

func (b *IntBuilder[T]) Between(minVal, maxVal T) *IntBuilder[T]

Between validates that the value is within a range (inclusive).

func (*IntBuilder[T]) Even

func (b *IntBuilder[T]) Even() *IntBuilder[T]

Even validates that the value is even.

func (*IntBuilder[T]) Max

func (b *IntBuilder[T]) Max(maxVal T) *IntBuilder[T]

Max validates that the value is at most the maximum.

func (*IntBuilder[T]) Min

func (b *IntBuilder[T]) Min(minVal T) *IntBuilder[T]

Min validates that the value is at least the minimum.

func (*IntBuilder[T]) MultipleOf

func (b *IntBuilder[T]) MultipleOf(divisor T) *IntBuilder[T]

MultipleOf validates that the value is a multiple of the divisor.

func (*IntBuilder[T]) Negative

func (b *IntBuilder[T]) Negative() *IntBuilder[T]

Negative validates that the value is less than zero.

func (*IntBuilder[T]) NonNegative

func (b *IntBuilder[T]) NonNegative() *IntBuilder[T]

NonNegative validates that the value is zero or greater.

func (*IntBuilder[T]) NonPositive

func (b *IntBuilder[T]) NonPositive() *IntBuilder[T]

NonPositive validates that the value is zero or less.

func (*IntBuilder[T]) NonZero

func (b *IntBuilder[T]) NonZero() *IntBuilder[T]

NonZero validates that the value is not zero.

func (*IntBuilder[T]) Odd

func (b *IntBuilder[T]) Odd() *IntBuilder[T]

Odd validates that the value is odd.

func (*IntBuilder[T]) Positive

func (b *IntBuilder[T]) Positive() *IntBuilder[T]

Positive validates that the value is greater than zero.

func (*IntBuilder[T]) V

func (b *IntBuilder[T]) V() *Validation

V returns the combined validation result.

func (*IntBuilder[T]) When

func (b *IntBuilder[T]) When(cond bool, fn func(*IntBuilder[T])) *IntBuilder[T]

When conditionally applies validations.

func (*IntBuilder[T]) Zero

func (b *IntBuilder[T]) Zero() *IntBuilder[T]

Zero validates that the value is exactly zero.

type Integer

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint for all integer types.

type NumBuilder

type NumBuilder[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

NumBuilder provides fluent validation for numeric values.

func Num

func Num[T constraints.Ordered](v T, field string) *NumBuilder[T]

Num creates a new numeric validation builder.

func (*NumBuilder[T]) Between

func (b *NumBuilder[T]) Between(minVal, maxVal T) *NumBuilder[T]

Between validates that the value is within a range (inclusive).

func (*NumBuilder[T]) BetweenExclusive

func (b *NumBuilder[T]) BetweenExclusive(minVal, maxVal T) *NumBuilder[T]

BetweenExclusive validates that the value is within a range (exclusive).

func (*NumBuilder[T]) GreaterThan

func (b *NumBuilder[T]) GreaterThan(threshold T) *NumBuilder[T]

GreaterThan validates that the value is strictly greater than the threshold.

func (*NumBuilder[T]) GreaterThanOrEqual

func (b *NumBuilder[T]) GreaterThanOrEqual(threshold T) *NumBuilder[T]

GreaterThanOrEqual validates that the value is >= the threshold.

func (*NumBuilder[T]) LessThan

func (b *NumBuilder[T]) LessThan(threshold T) *NumBuilder[T]

LessThan validates that the value is strictly less than the threshold.

func (*NumBuilder[T]) LessThanOrEqual

func (b *NumBuilder[T]) LessThanOrEqual(threshold T) *NumBuilder[T]

LessThanOrEqual validates that the value is <= the threshold.

func (*NumBuilder[T]) Max

func (b *NumBuilder[T]) Max(maxVal T) *NumBuilder[T]

Max validates that the value is at most the maximum.

func (*NumBuilder[T]) Min

func (b *NumBuilder[T]) Min(minVal T) *NumBuilder[T]

Min validates that the value is at least the minimum.

func (*NumBuilder[T]) NotOneOfValues

func (b *NumBuilder[T]) NotOneOfValues(disallowed []T) *NumBuilder[T]

NotOneOfValues validates that the value is not one of the disallowed values.

func (*NumBuilder[T]) OneOfValues

func (b *NumBuilder[T]) OneOfValues(allowed []T) *NumBuilder[T]

OneOfValues validates that the value is one of the allowed values.

func (*NumBuilder[T]) V

func (b *NumBuilder[T]) V() *Validation

V returns the combined validation result.

func (*NumBuilder[T]) When

func (b *NumBuilder[T]) When(cond bool, fn func(*NumBuilder[T])) *NumBuilder[T]

When conditionally applies validations.

type Number

type Number interface {
	Integer | Float
}

Number is a constraint for all numeric types.

type OptIntBuilder

type OptIntBuilder[T Integer] struct {
	// contains filtered or unexported fields
}

OptIntBuilder provides fluent validation for optional integer pointers.

func OptInt

func OptInt[T Integer](v *T, field string) *OptIntBuilder[T]

OptInt creates a new optional integer validation builder.

func (*OptIntBuilder[T]) Between

func (b *OptIntBuilder[T]) Between(minVal, maxVal T) *OptIntBuilder[T]

Between validates that the value is within a range (inclusive).

func (*OptIntBuilder[T]) Even

func (b *OptIntBuilder[T]) Even() *OptIntBuilder[T]

Even validates that the value is even.

func (*OptIntBuilder[T]) Max

func (b *OptIntBuilder[T]) Max(maxVal T) *OptIntBuilder[T]

Max validates that the value is at most the maximum.

func (*OptIntBuilder[T]) Min

func (b *OptIntBuilder[T]) Min(minVal T) *OptIntBuilder[T]

Min validates that the value is at least the minimum.

func (*OptIntBuilder[T]) MultipleOf

func (b *OptIntBuilder[T]) MultipleOf(divisor T) *OptIntBuilder[T]

MultipleOf validates that the value is a multiple of the divisor.

func (*OptIntBuilder[T]) NonNegative

func (b *OptIntBuilder[T]) NonNegative() *OptIntBuilder[T]

NonNegative validates that the value is zero or greater.

func (*OptIntBuilder[T]) NonZero

func (b *OptIntBuilder[T]) NonZero() *OptIntBuilder[T]

NonZero validates that the value is not zero.

func (*OptIntBuilder[T]) Odd

func (b *OptIntBuilder[T]) Odd() *OptIntBuilder[T]

Odd validates that the value is odd.

func (*OptIntBuilder[T]) Positive

func (b *OptIntBuilder[T]) Positive() *OptIntBuilder[T]

Positive validates that the value is greater than zero.

func (*OptIntBuilder[T]) V

func (b *OptIntBuilder[T]) V() *Validation

V returns the combined validation result.

func (*OptIntBuilder[T]) When

func (b *OptIntBuilder[T]) When(cond bool, fn func(*OptIntBuilder[T])) *OptIntBuilder[T]

When conditionally applies validations.

type OptNumBuilder

type OptNumBuilder[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

OptNumBuilder provides fluent validation for optional numeric pointers.

func OptNum

func OptNum[T constraints.Ordered](v *T, field string) *OptNumBuilder[T]

OptNum creates a new optional numeric validation builder.

func (*OptNumBuilder[T]) Between

func (b *OptNumBuilder[T]) Between(minVal, maxVal T) *OptNumBuilder[T]

Between validates that the value is within a range (inclusive).

func (*OptNumBuilder[T]) GreaterThan

func (b *OptNumBuilder[T]) GreaterThan(threshold T) *OptNumBuilder[T]

GreaterThan validates that the value is strictly greater than the threshold.

func (*OptNumBuilder[T]) LessThan

func (b *OptNumBuilder[T]) LessThan(threshold T) *OptNumBuilder[T]

LessThan validates that the value is strictly less than the threshold.

func (*OptNumBuilder[T]) Max

func (b *OptNumBuilder[T]) Max(maxVal T) *OptNumBuilder[T]

Max validates that the value is at most the maximum.

func (*OptNumBuilder[T]) Min

func (b *OptNumBuilder[T]) Min(minVal T) *OptNumBuilder[T]

Min validates that the value is at least the minimum.

func (*OptNumBuilder[T]) V

func (b *OptNumBuilder[T]) V() *Validation

V returns the combined validation result.

func (*OptNumBuilder[T]) When

func (b *OptNumBuilder[T]) When(cond bool, fn func(*OptNumBuilder[T])) *OptNumBuilder[T]

When conditionally applies validations.

type OptSliceBuilder

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

OptSliceBuilder provides fluent validation for optional slice pointers.

func OptSlice

func OptSlice[T any](v *[]T, field string) *OptSliceBuilder[T]

OptSlice creates a new optional slice validation builder.

func (*OptSliceBuilder[T]) EachV

func (b *OptSliceBuilder[T]) EachV(fn func(v T, field string) *Validation) *OptSliceBuilder[T]

EachV applies a validation to each element, collecting results.

func (*OptSliceBuilder[T]) ItemsBetween

func (b *OptSliceBuilder[T]) ItemsBetween(minItems, maxItems int) *OptSliceBuilder[T]

ItemsBetween validates slice length is within a range.

func (*OptSliceBuilder[T]) MaxItems

func (b *OptSliceBuilder[T]) MaxItems(n int) *OptSliceBuilder[T]

MaxItems validates maximum slice length.

func (*OptSliceBuilder[T]) MinItems

func (b *OptSliceBuilder[T]) MinItems(n int) *OptSliceBuilder[T]

MinItems validates minimum slice length.

func (*OptSliceBuilder[T]) NotEmpty

func (b *OptSliceBuilder[T]) NotEmpty() *OptSliceBuilder[T]

NotEmpty validates that the slice is not empty.

func (*OptSliceBuilder[T]) V

func (b *OptSliceBuilder[T]) V() *Validation

V returns the combined validation result.

func (*OptSliceBuilder[T]) When

func (b *OptSliceBuilder[T]) When(cond bool, fn func(*OptSliceBuilder[T])) *OptSliceBuilder[T]

When conditionally applies validations.

type OptStrBuilder

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

OptStrBuilder provides fluent validation for optional string pointers.

func OptStr

func OptStr(v *string, field string) *OptStrBuilder

OptStr creates a new optional string validation builder. If the pointer is nil, all validations are skipped (field is optional).

func (*OptStrBuilder) Alpha

func (b *OptStrBuilder) Alpha() *OptStrBuilder

Alpha validates that the string contains only ASCII letters.

func (*OptStrBuilder) AlphaNumeric

func (b *OptStrBuilder) AlphaNumeric() *OptStrBuilder

AlphaNumeric validates that the string contains only ASCII letters and digits.

func (*OptStrBuilder) Contains

func (b *OptStrBuilder) Contains(substr string) *OptStrBuilder

Contains validates that the string contains the substring.

func (*OptStrBuilder) Email

func (b *OptStrBuilder) Email() *OptStrBuilder

Email validates that the string is a valid email address.

func (*OptStrBuilder) Len

func (b *OptStrBuilder) Len(n int) *OptStrBuilder

Len validates exact string length.

func (*OptStrBuilder) LenBetween

func (b *OptStrBuilder) LenBetween(minLen, maxLen int) *OptStrBuilder

LenBetween validates string length is within a range.

func (*OptStrBuilder) LowerCase

func (b *OptStrBuilder) LowerCase() *OptStrBuilder

LowerCase validates that the string is entirely lowercase.

func (*OptStrBuilder) Match

func (b *OptStrBuilder) Match(pattern *regexp.Regexp) *OptStrBuilder

Match validates that the string matches a pattern.

func (*OptStrBuilder) MaxLen

func (b *OptStrBuilder) MaxLen(n int) *OptStrBuilder

MaxLen validates maximum string length.

func (*OptStrBuilder) MinLen

func (b *OptStrBuilder) MinLen(n int) *OptStrBuilder

MinLen validates minimum string length.

func (*OptStrBuilder) NotContains

func (b *OptStrBuilder) NotContains(substr string) *OptStrBuilder

NotContains validates that the string does not contain the substring.

func (*OptStrBuilder) NotMatch

func (b *OptStrBuilder) NotMatch(pattern *regexp.Regexp) *OptStrBuilder

NotMatch validates that the string does not match a pattern.

func (*OptStrBuilder) NotOneOf

func (b *OptStrBuilder) NotOneOf(disallowed []string) *OptStrBuilder

NotOneOf validates that the string is not one of the disallowed values.

func (*OptStrBuilder) Numeric

func (b *OptStrBuilder) Numeric() *OptStrBuilder

Numeric validates that the string contains only digits.

func (*OptStrBuilder) OneOf

func (b *OptStrBuilder) OneOf(allowed []string) *OptStrBuilder

OneOf validates that the string is one of the allowed values.

func (*OptStrBuilder) Prefix

func (b *OptStrBuilder) Prefix(prefix string) *OptStrBuilder

Prefix validates that the string starts with the given prefix.

func (*OptStrBuilder) SingleLine

func (b *OptStrBuilder) SingleLine() *OptStrBuilder

SingleLine validates that the string contains no newlines.

func (*OptStrBuilder) Slug

func (b *OptStrBuilder) Slug() *OptStrBuilder

Slug validates that the string is a valid URL slug.

func (*OptStrBuilder) Suffix

func (b *OptStrBuilder) Suffix(suffix string) *OptStrBuilder

Suffix validates that the string ends with the given suffix.

func (*OptStrBuilder) Trimmed

func (b *OptStrBuilder) Trimmed() *OptStrBuilder

Trimmed validates that the string has no leading or trailing whitespace.

func (*OptStrBuilder) URL

func (b *OptStrBuilder) URL() *OptStrBuilder

URL validates that the string is a valid URL.

func (*OptStrBuilder) UUID

func (b *OptStrBuilder) UUID() *OptStrBuilder

UUID validates that the string is a valid UUID.

func (*OptStrBuilder) UUID4

func (b *OptStrBuilder) UUID4() *OptStrBuilder

UUID4 validates that the string is a valid UUID v4.

func (*OptStrBuilder) UpperCase

func (b *OptStrBuilder) UpperCase() *OptStrBuilder

UpperCase validates that the string is entirely uppercase.

func (*OptStrBuilder) V

func (b *OptStrBuilder) V() *Validation

V returns the combined validation result. Returns nil if the value is nil (optional field not provided).

func (*OptStrBuilder) When

func (b *OptStrBuilder) When(cond bool, fn func(*OptStrBuilder)) *OptStrBuilder

When conditionally applies validations.

type OptStrSliceBuilder

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

OptStrSliceBuilder provides fluent validation for optional string slice pointers.

func OptStrSlice

func OptStrSlice(v *[]string, field string) *OptStrSliceBuilder

OptStrSlice creates a new optional string slice validation builder.

func (*OptStrSliceBuilder) AllMaxLen

func (b *OptStrSliceBuilder) AllMaxLen(n int) *OptStrSliceBuilder

AllMaxLen validates that all elements have at most n characters.

func (*OptStrSliceBuilder) AllNotBlank

func (b *OptStrSliceBuilder) AllNotBlank() *OptStrSliceBuilder

AllNotBlank validates that no element is blank.

func (*OptStrSliceBuilder) Each

func (b *OptStrSliceBuilder) Each(fn func(*StrBuilder)) *OptStrSliceBuilder

Each applies validations to each element via a StrBuilder.

func (*OptStrSliceBuilder) MaxItems

func (b *OptStrSliceBuilder) MaxItems(n int) *OptStrSliceBuilder

MaxItems validates maximum slice length.

func (*OptStrSliceBuilder) MinItems

func (b *OptStrSliceBuilder) MinItems(n int) *OptStrSliceBuilder

MinItems validates minimum slice length.

func (*OptStrSliceBuilder) NotEmpty

func (b *OptStrSliceBuilder) NotEmpty() *OptStrSliceBuilder

NotEmpty validates that the slice is not empty.

func (*OptStrSliceBuilder) Unique

Unique validates that all elements are unique.

func (*OptStrSliceBuilder) V

V returns the combined validation result.

func (*OptStrSliceBuilder) When

When conditionally applies validations.

type Result

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

Result contains the aggregated outcome of multiple validations.

func All

func All(validations ...*Validation) *Result

All collects all validations and returns a Result. Tracks both successful and failed validations for metadata purposes.

func Check

func Check[T any](validations ...*Validation) *Result

Check validates the given validations and verifies that all fields with validate tags were checked. This is the primary API for struct validation - it combines validation execution with tag verification.

Usage:

func (r *Request) Validate() error {
    return check.Check[Request](
        check.Str(r.Email, "email").Required().Email().V(),
        check.Str(r.Name, "name").Required().V(),
    ).Err()
}

func Each

func Each[T any](v []T, fn func(T, int) *Validation) *Result

Each applies a validation function to each element in a slice. Returns a Result with all validations collected from each element.

func EachEntry

func EachEntry[K comparable, V any](v map[K]V, fn func(K, V) *Validation) *Result

EachEntry applies a validation function to each key-value pair in a map.

func EachKey

func EachKey[K comparable, V any](v map[K]V, fn func(K) *Validation) *Result

EachKey applies a validation function to each key in a map.

func EachMapValue

func EachMapValue[K comparable, V any](v map[K]V, fn func(V) *Validation) *Result

EachMapValue applies a validation function to each value in a map.

func EachValue

func EachValue[T any](v []T, fn func(T) *Validation) *Result

EachValue applies a simple validation function (no index) to each element.

func First

func First(validations ...*Validation) *Result

First returns a Result with the first failed validation, or nil error if all pass. Still tracks all validations that were attempted up to and including the failure.

func Merge

func Merge(results ...*Result) *Result

Merge combines multiple Results into one.

func (*Result) Applied

func (r *Result) Applied() map[string][]string

Applied returns a map of field names to validator names that were executed.

func (*Result) Err

func (r *Result) Err() error

Err returns the validation error (nil if validation passed).

func (*Result) Error

func (r *Result) Error() string

Error implements the error interface for convenience.

func (*Result) Fields

func (r *Result) Fields() []string

Fields returns all field names that had validators applied.

func (*Result) HasValidator

func (r *Result) HasValidator(field, validator string) bool

HasValidator checks if a specific validator was applied to a field.

func (*Result) Unwrap

func (r *Result) Unwrap() error

Unwrap implements errors.Unwrap for compatibility.

func (*Result) ValidatorsFor

func (r *Result) ValidatorsFor(field string) []string

ValidatorsFor returns all validators applied to a specific field.

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint for signed numeric types.

type SliceBuilder

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

SliceBuilder provides fluent validation for slice values.

func Slice

func Slice[T any](v []T, field string) *SliceBuilder[T]

Slice creates a new slice validation builder.

func (*SliceBuilder[T]) Each

func (b *SliceBuilder[T]) Each(fn func(v T, field string) *Validation) *SliceBuilder[T]

Each applies a validation function to each element, collecting results. The function receives the element and auto-generated field name "field[i]". Returns *Validation for each element; non-nil results are collected.

func (*SliceBuilder[T]) EachV

func (b *SliceBuilder[T]) EachV(fn func(v T, field string) *Validation) *SliceBuilder[T]

EachV applies a validation to each element, collecting results. The function receives the element and auto-generated field name.

func (*SliceBuilder[T]) Empty

func (b *SliceBuilder[T]) Empty() *SliceBuilder[T]

Empty validates that the slice is empty.

func (*SliceBuilder[T]) ExactItems

func (b *SliceBuilder[T]) ExactItems(n int) *SliceBuilder[T]

ExactItems validates exact slice length.

func (*SliceBuilder[T]) ItemsBetween

func (b *SliceBuilder[T]) ItemsBetween(minItems, maxItems int) *SliceBuilder[T]

ItemsBetween validates slice length is within a range.

func (*SliceBuilder[T]) MaxItems

func (b *SliceBuilder[T]) MaxItems(n int) *SliceBuilder[T]

MaxItems validates maximum slice length.

func (*SliceBuilder[T]) MinItems

func (b *SliceBuilder[T]) MinItems(n int) *SliceBuilder[T]

MinItems validates minimum slice length.

func (*SliceBuilder[T]) NotEmpty

func (b *SliceBuilder[T]) NotEmpty() *SliceBuilder[T]

NotEmpty validates that the slice is not empty.

func (*SliceBuilder[T]) V

func (b *SliceBuilder[T]) V() *Validation

V returns the combined validation result.

func (*SliceBuilder[T]) When

func (b *SliceBuilder[T]) When(cond bool, fn func(*SliceBuilder[T])) *SliceBuilder[T]

When conditionally applies validations.

type StrBuilder

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

StrBuilder provides fluent validation for string values.

func Str

func Str(v string, field string) *StrBuilder

Str creates a new string validation builder.

func (*StrBuilder) ASCII

func (b *StrBuilder) ASCII() *StrBuilder

ASCII validates that the string contains only ASCII characters.

func (*StrBuilder) Alpha

func (b *StrBuilder) Alpha() *StrBuilder

Alpha validates that the string contains only ASCII letters.

func (*StrBuilder) AlphaNumeric

func (b *StrBuilder) AlphaNumeric() *StrBuilder

AlphaNumeric validates that the string contains only ASCII letters and digits.

func (*StrBuilder) AlphaNumericUnicode

func (b *StrBuilder) AlphaNumericUnicode() *StrBuilder

AlphaNumericUnicode validates that the string contains only Unicode letters and digits.

func (*StrBuilder) AlphaUnicode

func (b *StrBuilder) AlphaUnicode() *StrBuilder

AlphaUnicode validates that the string contains only Unicode letters.

func (*StrBuilder) Base64

func (b *StrBuilder) Base64() *StrBuilder

Base64 validates that the string is valid base64.

func (*StrBuilder) Base64URL

func (b *StrBuilder) Base64URL() *StrBuilder

Base64URL validates that the string is valid URL-safe base64.

func (*StrBuilder) CIDR

func (b *StrBuilder) CIDR() *StrBuilder

CIDR validates that the string is a valid CIDR notation.

func (*StrBuilder) Contains

func (b *StrBuilder) Contains(substr string) *StrBuilder

Contains validates that the string contains the substring.

func (*StrBuilder) CountryCode2

func (b *StrBuilder) CountryCode2() *StrBuilder

CountryCode2 validates that the string is a valid ISO 3166-1 alpha-2 country code.

func (*StrBuilder) CountryCode3

func (b *StrBuilder) CountryCode3() *StrBuilder

CountryCode3 validates that the string is a valid ISO 3166-1 alpha-3 country code.

func (*StrBuilder) CreditCard

func (b *StrBuilder) CreditCard() *StrBuilder

CreditCard validates that the string is a valid credit card number.

func (*StrBuilder) CurrencyCode

func (b *StrBuilder) CurrencyCode() *StrBuilder

CurrencyCode validates that the string is a valid ISO 4217 currency code.

func (*StrBuilder) DataURI

func (b *StrBuilder) DataURI() *StrBuilder

DataURI validates that the string is a valid data URI.

func (*StrBuilder) E164

func (b *StrBuilder) E164() *StrBuilder

E164 validates that the string is a valid E.164 phone number.

func (*StrBuilder) Email

func (b *StrBuilder) Email() *StrBuilder

Email validates that the string is a valid email address.

func (*StrBuilder) FilePath

func (b *StrBuilder) FilePath() *StrBuilder

FilePath validates that the string is a valid file path.

func (*StrBuilder) HTTPOrHTTPS

func (b *StrBuilder) HTTPOrHTTPS() *StrBuilder

HTTPOrHTTPS validates that the string is a valid HTTP or HTTPS URL.

func (*StrBuilder) Hex

func (b *StrBuilder) Hex() *StrBuilder

Hex validates that the string contains only hexadecimal characters.

func (*StrBuilder) HexColor

func (b *StrBuilder) HexColor() *StrBuilder

HexColor validates that the string is a valid hex color.

func (*StrBuilder) HexColorFull

func (b *StrBuilder) HexColorFull() *StrBuilder

HexColorFull validates that the string is a valid 6-digit hex color.

func (*StrBuilder) HostPort

func (b *StrBuilder) HostPort() *StrBuilder

HostPort validates that the string is a valid host:port combination.

func (*StrBuilder) Hostname

func (b *StrBuilder) Hostname() *StrBuilder

Hostname validates that the string is a valid hostname.

func (*StrBuilder) IP

func (b *StrBuilder) IP() *StrBuilder

IP validates that the string is a valid IP address.

func (*StrBuilder) IPv4

func (b *StrBuilder) IPv4() *StrBuilder

IPv4 validates that the string is a valid IPv4 address.

func (*StrBuilder) IPv6

func (b *StrBuilder) IPv6() *StrBuilder

IPv6 validates that the string is a valid IPv6 address.

func (*StrBuilder) Identifier

func (b *StrBuilder) Identifier() *StrBuilder

Identifier validates that the string is a valid identifier.

func (*StrBuilder) JSON

func (b *StrBuilder) JSON() *StrBuilder

JSON validates that the string is valid JSON.

func (*StrBuilder) LanguageCode

func (b *StrBuilder) LanguageCode() *StrBuilder

LanguageCode validates that the string is a valid ISO 639-1 language code.

func (*StrBuilder) Latitude

func (b *StrBuilder) Latitude() *StrBuilder

Latitude validates that the string is a valid latitude.

func (*StrBuilder) Len

func (b *StrBuilder) Len(n int) *StrBuilder

Len validates exact string length.

func (*StrBuilder) LenBetween

func (b *StrBuilder) LenBetween(minLen, maxLen int) *StrBuilder

LenBetween validates string length is within a range.

func (*StrBuilder) Longitude

func (b *StrBuilder) Longitude() *StrBuilder

Longitude validates that the string is a valid longitude.

func (*StrBuilder) LowerCase

func (b *StrBuilder) LowerCase() *StrBuilder

LowerCase validates that the string is entirely lowercase.

func (*StrBuilder) MAC

func (b *StrBuilder) MAC() *StrBuilder

MAC validates that the string is a valid MAC address.

func (*StrBuilder) Match

func (b *StrBuilder) Match(pattern *regexp.Regexp) *StrBuilder

Match validates that the string matches a pattern.

func (*StrBuilder) MaxLen

func (b *StrBuilder) MaxLen(n int) *StrBuilder

MaxLen validates maximum string length.

func (*StrBuilder) MinLen

func (b *StrBuilder) MinLen(n int) *StrBuilder

MinLen validates minimum string length.

func (*StrBuilder) NoWhitespace

func (b *StrBuilder) NoWhitespace() *StrBuilder

NoWhitespace validates that the string contains no whitespace.

func (*StrBuilder) NotBlank

func (b *StrBuilder) NotBlank() *StrBuilder

NotBlank validates that the string is not empty or whitespace-only.

func (*StrBuilder) NotContains

func (b *StrBuilder) NotContains(substr string) *StrBuilder

NotContains validates that the string does not contain the substring.

func (*StrBuilder) NotMatch

func (b *StrBuilder) NotMatch(pattern *regexp.Regexp) *StrBuilder

NotMatch validates that the string does not match a pattern.

func (*StrBuilder) NotOneOf

func (b *StrBuilder) NotOneOf(disallowed []string) *StrBuilder

NotOneOf validates that the string is not one of the disallowed values.

func (*StrBuilder) Numeric

func (b *StrBuilder) Numeric() *StrBuilder

Numeric validates that the string contains only digits.

func (*StrBuilder) OneOf

func (b *StrBuilder) OneOf(allowed []string) *StrBuilder

OneOf validates that the string is one of the allowed values.

func (*StrBuilder) Port

func (b *StrBuilder) Port() *StrBuilder

Port validates that the string is a valid port number.

func (*StrBuilder) Prefix

func (b *StrBuilder) Prefix(prefix string) *StrBuilder

Prefix validates that the string starts with the given prefix.

func (*StrBuilder) PrintableASCII

func (b *StrBuilder) PrintableASCII() *StrBuilder

PrintableASCII validates that the string contains only printable ASCII.

func (*StrBuilder) Required

func (b *StrBuilder) Required() *StrBuilder

Required validates that the string is not empty.

func (*StrBuilder) Semver

func (b *StrBuilder) Semver() *StrBuilder

Semver validates that the string is a valid semantic version.

func (*StrBuilder) SingleLine

func (b *StrBuilder) SingleLine() *StrBuilder

SingleLine validates that the string contains no newlines.

func (*StrBuilder) Slug

func (b *StrBuilder) Slug() *StrBuilder

Slug validates that the string is a valid URL slug.

func (*StrBuilder) Suffix

func (b *StrBuilder) Suffix(suffix string) *StrBuilder

Suffix validates that the string ends with the given suffix.

func (*StrBuilder) Trimmed

func (b *StrBuilder) Trimmed() *StrBuilder

Trimmed validates that the string has no leading or trailing whitespace.

func (*StrBuilder) URL

func (b *StrBuilder) URL() *StrBuilder

URL validates that the string is a valid URL.

func (*StrBuilder) URLWithScheme

func (b *StrBuilder) URLWithScheme(schemes []string) *StrBuilder

URLWithScheme validates that the string is a valid URL with one of the given schemes.

func (*StrBuilder) UUID

func (b *StrBuilder) UUID() *StrBuilder

UUID validates that the string is a valid UUID.

func (*StrBuilder) UUID4

func (b *StrBuilder) UUID4() *StrBuilder

UUID4 validates that the string is a valid UUID v4.

func (*StrBuilder) UnixPath

func (b *StrBuilder) UnixPath() *StrBuilder

UnixPath validates that the string is a valid Unix path.

func (*StrBuilder) UpperCase

func (b *StrBuilder) UpperCase() *StrBuilder

UpperCase validates that the string is entirely uppercase.

func (*StrBuilder) V

func (b *StrBuilder) V() *Validation

V returns the combined validation result.

func (*StrBuilder) When

func (b *StrBuilder) When(cond bool, fn func(*StrBuilder)) *StrBuilder

When conditionally applies validations.

type StrSliceBuilder

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

StrSliceBuilder provides fluent validation for string slices.

func StrSlice

func StrSlice(v []string, field string) *StrSliceBuilder

StrSlice creates a new string slice validation builder.

func (*StrSliceBuilder) AllMaxLen

func (b *StrSliceBuilder) AllMaxLen(n int) *StrSliceBuilder

AllMaxLen validates that all elements have at most n characters.

func (*StrSliceBuilder) AllMinLen

func (b *StrSliceBuilder) AllMinLen(n int) *StrSliceBuilder

AllMinLen validates that all elements have at least n characters.

func (*StrSliceBuilder) AllNotBlank

func (b *StrSliceBuilder) AllNotBlank() *StrSliceBuilder

AllNotBlank validates that no element is blank.

func (*StrSliceBuilder) Each

func (b *StrSliceBuilder) Each(fn func(*StrBuilder)) *StrSliceBuilder

Each applies validations to each element via a StrBuilder. Field names are auto-generated as "field[i]".

func (*StrSliceBuilder) ItemsBetween

func (b *StrSliceBuilder) ItemsBetween(minItems, maxItems int) *StrSliceBuilder

ItemsBetween validates slice length is within a range.

func (*StrSliceBuilder) MaxItems

func (b *StrSliceBuilder) MaxItems(n int) *StrSliceBuilder

MaxItems validates maximum slice length.

func (*StrSliceBuilder) MinItems

func (b *StrSliceBuilder) MinItems(n int) *StrSliceBuilder

MinItems validates minimum slice length.

func (*StrSliceBuilder) NotEmpty

func (b *StrSliceBuilder) NotEmpty() *StrSliceBuilder

NotEmpty validates that the slice is not empty.

func (*StrSliceBuilder) Unique

func (b *StrSliceBuilder) Unique() *StrSliceBuilder

Unique validates that all elements are unique.

func (*StrSliceBuilder) V

func (b *StrSliceBuilder) V() *Validation

V returns the combined validation result.

func (*StrSliceBuilder) When

func (b *StrSliceBuilder) When(cond bool, fn func(*StrSliceBuilder)) *StrSliceBuilder

When conditionally applies validations.

type UncheckedFieldError

type UncheckedFieldError struct {
	Field       string // The field name used in validation (json tag or lowercase)
	StructField string // The actual struct field name
	Tag         string // The validate tag value
}

UncheckedFieldError indicates a field has validation requirements but was not validated.

func (*UncheckedFieldError) Error

func (e *UncheckedFieldError) Error() string

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint for unsigned numeric types.

type Validation

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

Validation represents the result of a single validation check. It tracks both the outcome (error or nil) and metadata about what was validated.

func ASCII

func ASCII(v, field string) *Validation

ASCII validates that a string contains only ASCII characters.

func After

func After(v, t time.Time, field string) *Validation

After validates that a time is after the given time.

func AfterNow

func AfterNow(v time.Time, field string) *Validation

AfterNow validates that a time is after the current time.

func AfterOrEqual

func AfterOrEqual(v, t time.Time, field string) *Validation

AfterOrEqual validates that a time is after or equal to the given time.

func AfterOrEqualNow

func AfterOrEqualNow(v time.Time, field string) *Validation

AfterOrEqualNow validates that a time is after or equal to the current time.

func AllSatisfy

func AllSatisfy[T any](v []T, pred func(T) bool, field, message string) *Validation

AllSatisfy validates that all elements satisfy a predicate.

func Alpha

func Alpha(v, field string) *Validation

Alpha validates that a string contains only ASCII letters.

func AlphaNumeric

func AlphaNumeric(v, field string) *Validation

AlphaNumeric validates that a string contains only ASCII letters and digits.

func AlphaNumericUnicode

func AlphaNumericUnicode(v, field string) *Validation

AlphaNumericUnicode validates that a string contains only Unicode letters and digits.

func AlphaUnicode

func AlphaUnicode(v, field string) *Validation

AlphaUnicode validates that a string contains only Unicode letters.

func AnySatisfies

func AnySatisfies[T any](v []T, pred func(T) bool, field, message string) *Validation

AnySatisfies validates that at least one element satisfies a predicate.

func Base64

func Base64(v, field string) *Validation

Base64 validates that a string is valid base64.

func Base64URL

func Base64URL(v, field string) *Validation

Base64URL validates that a string is valid URL-safe base64.

func Before

func Before(v, t time.Time, field string) *Validation

Before validates that a time is before the given time.

func BeforeNow

func BeforeNow(v time.Time, field string) *Validation

BeforeNow validates that a time is before the current time.

func BeforeOrEqual

func BeforeOrEqual(v, t time.Time, field string) *Validation

BeforeOrEqual validates that a time is before or equal to the given time.

func BeforeOrEqualNow

func BeforeOrEqualNow(v time.Time, field string) *Validation

BeforeOrEqualNow validates that a time is before or equal to the current time.

func Between

func Between[T constraints.Ordered](v, minVal, maxVal T, field string) *Validation

Between validates that a value is within a range (inclusive).

func BetweenExclusive

func BetweenExclusive[T constraints.Ordered](v, minVal, maxVal T, field string) *Validation

BetweenExclusive validates that a value is within a range (exclusive).

func BetweenTime

func BetweenTime(v, start, end time.Time, field string) *Validation

BetweenTime validates that a time is within a range (inclusive).

func BetweenTimeExclusive

func BetweenTimeExclusive(v, start, end time.Time, field string) *Validation

BetweenTimeExclusive validates that a time is within a range (exclusive).

func CIDR

func CIDR(v, field string) *Validation

CIDR validates that a string is a valid CIDR notation.

func Contains

func Contains(v, substr, field string) *Validation

Contains validates that a string contains the given substring.

func ContainsAll

func ContainsAll[T comparable](v []T, required []T, field string) *Validation

ContainsAll validates that a slice contains all the given elements.

func ContainsAny

func ContainsAny[T comparable](v []T, options []T, field string) *Validation

ContainsAny validates that a slice contains at least one of the given elements.

func ContainsNone

func ContainsNone[T comparable](v []T, forbidden []T, field string) *Validation

ContainsNone validates that a slice contains none of the given elements.

func CountryCode2

func CountryCode2(v, field string) *Validation

CountryCode2 validates that a string is a valid ISO 3166-1 alpha-2 country code.

func CountryCode3

func CountryCode3(v, field string) *Validation

CountryCode3 validates that a string is a valid ISO 3166-1 alpha-3 country code.

func CreditCard

func CreditCard(v, field string) *Validation

CreditCard validates that a string is a valid credit card number using the Luhn algorithm.

func CurrencyCode

func CurrencyCode(v, field string) *Validation

CurrencyCode validates that a string is a valid ISO 4217 currency code.

func DataURI

func DataURI(v, field string) *Validation

DataURI validates that a string is a valid data URI.

func DefaultOr

func DefaultOr[T any](v *T, defaultVal T, fn func(T) *Validation) *Validation

DefaultOr uses a default value if the pointer is nil, then validates.

func Disjoint

func Disjoint[T comparable](v, other []T, field string) *Validation

Disjoint validates that v shares no elements with other.

func DurationBetween

func DurationBetween(v, minDur, maxDur time.Duration, field string) *Validation

DurationBetween validates that a duration is within a range (inclusive).

func DurationMax

func DurationMax(v, maxDur time.Duration, field string) *Validation

DurationMax validates that a duration is at most the maximum.

func DurationMin

func DurationMin(v, minDur time.Duration, field string) *Validation

DurationMin validates that a duration is at least the minimum.

func DurationNonNegative

func DurationNonNegative(v time.Duration, field string) *Validation

DurationNonNegative validates that a duration is non-negative.

func DurationPositive

func DurationPositive(v time.Duration, field string) *Validation

DurationPositive validates that a duration is positive.

func E164

func E164(v, field string) *Validation

E164 validates that a string is a valid E.164 phone number.

func Email

func Email(v, field string) *Validation

Email validates that a string is a valid email address.

func Empty

func Empty[T any](v []T, field string) *Validation

Empty validates that a slice is empty.

func EmptyMap

func EmptyMap[K comparable, V any](v map[K]V, field string) *Validation

EmptyMap validates that a map is empty.

func Equal

func Equal[T comparable](v, expected T, field string) *Validation

Equal validates that two values are equal.

func EqualField

func EqualField[T comparable](v, other T, field, otherField string) *Validation

EqualField validates that a value equals another field's value. Useful for password confirmation, etc.

func Even

func Even[T Integer](v T, field string) *Validation

Even validates that an integer value is even.

func ExactItems

func ExactItems[T any](v []T, count int, field string) *Validation

ExactItems validates exact slice length.

func ExactKeys

func ExactKeys[K comparable, V any](v map[K]V, count int, field string) *Validation

ExactKeys validates exact number of keys in a map.

func FilePath

func FilePath(v, field string) *Validation

FilePath validates that a string looks like a file path (contains path separators).

func GreaterThan

func GreaterThan[T constraints.Ordered](v, threshold T, field string) *Validation

GreaterThan validates that a value is strictly greater than the threshold.

func GreaterThanField

func GreaterThanField[T constraints.Ordered](v, other T, field, otherField string) *Validation

GreaterThanField validates that a value is greater than another field's value.

func GreaterThanOrEqual

func GreaterThanOrEqual[T constraints.Ordered](v, threshold T, field string) *Validation

GreaterThanOrEqual validates that a value is greater than or equal to the threshold.

func GreaterThanOrEqualField

func GreaterThanOrEqualField[T constraints.Ordered](v, other T, field, otherField string) *Validation

GreaterThanOrEqualField validates that a value is greater than or equal to another field's value.

func HTTPOrHTTPS

func HTTPOrHTTPS(v, field string) *Validation

HTTPOrHTTPS validates that a string is a valid HTTP or HTTPS URL.

func HTTPStatusCode

func HTTPStatusCode(v int, field string) *Validation

HTTPStatusCode validates that a value is a valid HTTP status code (100-599).

func HasAnyKey

func HasAnyKey[K comparable, V any](v map[K]V, keys []K, field string) *Validation

HasAnyKey validates that a map contains at least one of the given keys.

func HasKey

func HasKey[K comparable, V any](v map[K]V, key K, field string) *Validation

HasKey validates that a map contains the given key.

func HasKeys

func HasKeys[K comparable, V any](v map[K]V, keys []K, field string) *Validation

HasKeys validates that a map contains all the given keys.

func Hex

func Hex(v, field string) *Validation

Hex validates that a string contains only hexadecimal characters.

func HexColor

func HexColor(v, field string) *Validation

HexColor validates that a string is a valid hex color (#RGB, #RRGGBB, or #RRGGBBAA).

func HexColorFull

func HexColorFull(v, field string) *Validation

HexColorFull validates that a string is a valid 6-digit hex color (#RRGGBB).

func HostPort

func HostPort(v, field string) *Validation

HostPort validates that a string is a valid host:port combination.

func Hostname

func Hostname(v, field string) *Validation

Hostname validates that a string is a valid hostname.

func IP

func IP(v, field string) *Validation

IP validates that a string is a valid IP address (v4 or v6).

func IPv4

func IPv4(v, field string) *Validation

IPv4 validates that a string is a valid IPv4 address.

func IPv6

func IPv6(v, field string) *Validation

IPv6 validates that a string is a valid IPv6 address.

func Identifier

func Identifier(v, field string) *Validation

Identifier validates that a string is a valid identifier (letter/underscore start, alphanumeric/underscore body).

func InFuture

func InFuture(v time.Time, field string) *Validation

InFuture is an alias for AfterNow.

func InPast

func InPast(v time.Time, field string) *Validation

InPast is an alias for BeforeNow.

func IsWeekend

func IsWeekend(v time.Time, field string) *Validation

IsWeekend validates that a time is on Saturday or Sunday.

func ItemsBetween

func ItemsBetween[T any](v []T, minCount, maxCount int, field string) *Validation

ItemsBetween validates slice length is within a range (inclusive).

func JSON

func JSON(v, field string) *Validation

JSON validates that a string is valid JSON.

func KeysBetween

func KeysBetween[K comparable, V any](v map[K]V, minKeys, maxKeys int, field string) *Validation

KeysBetween validates map size is within a range (inclusive).

func LanguageCode

func LanguageCode(v, field string) *Validation

LanguageCode validates that a string is a valid ISO 639-1 language code.

func Latitude

func Latitude(v, field string) *Validation

Latitude validates that a string is a valid latitude (-90 to 90).

func Len

func Len(v string, exact int, field string) *Validation

Len validates exact string length (in runes, not bytes).

func LenBetween

func LenBetween(v string, minLen, maxLen int, field string) *Validation

LenBetween validates string length is within a range (inclusive).

func LessThan

func LessThan[T constraints.Ordered](v, threshold T, field string) *Validation

LessThan validates that a value is strictly less than the threshold.

func LessThanField

func LessThanField[T constraints.Ordered](v, other T, field, otherField string) *Validation

LessThanField validates that a value is less than another field's value.

func LessThanOrEqual

func LessThanOrEqual[T constraints.Ordered](v, threshold T, field string) *Validation

LessThanOrEqual validates that a value is less than or equal to the threshold.

func LessThanOrEqualField

func LessThanOrEqualField[T constraints.Ordered](v, other T, field, otherField string) *Validation

LessThanOrEqualField validates that a value is less than or equal to another field's value.

func Longitude

func Longitude(v, field string) *Validation

Longitude validates that a string is a valid longitude (-180 to 180).

func LowerCase

func LowerCase(v, field string) *Validation

LowerCase validates that a string is entirely lowercase.

func MAC

func MAC(v, field string) *Validation

MAC validates that a string is a valid MAC address.

func Match

func Match(v string, pattern *regexp.Regexp, field string) *Validation

Match validates that a string matches a regular expression.

func Max

func Max[T constraints.Ordered](v, maxVal T, field string) *Validation

Max validates that a value is at most the maximum.

func MaxItems

func MaxItems[T any](v []T, maxCount int, field string) *Validation

MaxItems validates maximum slice length.

func MaxKeys

func MaxKeys[K comparable, V any](v map[K]V, maxKeys int, field string) *Validation

MaxKeys validates maximum number of keys in a map.

func MaxLen

func MaxLen(v string, maxLen int, field string) *Validation

MaxLen validates maximum string length (in runes, not bytes).

func Min

func Min[T constraints.Ordered](v, minVal T, field string) *Validation

Min validates that a value is at least the minimum.

func MinItems

func MinItems[T any](v []T, minCount int, field string) *Validation

MinItems validates minimum slice length.

func MinKeys

func MinKeys[K comparable, V any](v map[K]V, minKeys int, field string) *Validation

MinKeys validates minimum number of keys in a map.

func MinLen

func MinLen(v string, minLen int, field string) *Validation

MinLen validates minimum string length (in runes, not bytes).

func MultipleOf

func MultipleOf[T Integer](v, divisor T, field string) *Validation

MultipleOf validates that a value is a multiple of the given divisor.

func Negative

func Negative[T Signed | Float](v T, field string) *Validation

Negative validates that a value is less than zero.

func Nil

func Nil[T any](v *T, field string) *Validation

Nil validates that a pointer is nil.

func NilOr

func NilOr[T any](v *T, fn func(T) *Validation) *Validation

NilOr validates a pointer value if it's not nil. If the pointer is nil, returns nil (no validation applied - field is optional). If the pointer is not nil, applies the given validation function.

func NilOrField

func NilOrField[T any](v *T, fn func(T, string) *Validation, field string) *Validation

NilOrField is like NilOr but includes field context in the error.

func NoWhitespace

func NoWhitespace(v, field string) *Validation

NoWhitespace validates that a string contains no whitespace characters.

func NonNegative

func NonNegative[T Signed | Float](v T, field string) *Validation

NonNegative validates that a value is zero or greater.

func NonPositive

func NonPositive[T Signed | Float](v T, field string) *Validation

NonPositive validates that a value is zero or less.

func NonZero

func NonZero[T Number](v T, field string) *Validation

NonZero validates that a value is not zero.

func NoneSatisfy

func NoneSatisfy[T any](v []T, pred func(T) bool, field, message string) *Validation

NoneSatisfy validates that no elements satisfy a predicate.

func NotBlank

func NotBlank(v, field string) *Validation

NotBlank validates that a string is not empty or whitespace-only. Unlike Required, this does not trim - it checks the raw value.

func NotContains

func NotContains(v, substr, field string) *Validation

NotContains validates that a string does not contain the given substring.

func NotEmpty

func NotEmpty[T any](v []T, field string) *Validation

NotEmpty validates that a slice is not empty.

func NotEmptyMap

func NotEmptyMap[K comparable, V any](v map[K]V, field string) *Validation

NotEmptyMap validates that a map is not empty.

func NotEqual

func NotEqual[T comparable](v, other T, field string) *Validation

NotEqual validates that two values are not equal.

func NotEqualField

func NotEqualField[T comparable](v, other T, field, otherField string) *Validation

NotEqualField validates that a value does not equal another field's value.

func NotHasKey

func NotHasKey[K comparable, V any](v map[K]V, key K, field string) *Validation

NotHasKey validates that a map does not contain the given key.

func NotHasKeys

func NotHasKeys[K comparable, V any](v map[K]V, keys []K, field string) *Validation

NotHasKeys validates that a map does not contain any of the given keys.

func NotMatch

func NotMatch(v string, pattern *regexp.Regexp, field string) *Validation

NotMatch validates that a string does not match a regular expression.

func NotNil

func NotNil[T any](v *T, field string) *Validation

NotNil validates that a pointer is not nil.

func NotNilInterface

func NotNilInterface(v any, field string) *Validation

NotNilInterface validates that an interface value is not nil.

func NotOneOf

func NotOneOf(v string, disallowed []string, field string) *Validation

NotOneOf validates that a string is not one of the disallowed values.

func NotOneOfValues

func NotOneOfValues[T comparable](v T, disallowed []T, field string) *Validation

NotOneOfValues validates that a value is not one of the disallowed values.

func NotWeekend

func NotWeekend(v time.Time, field string) *Validation

NotWeekend validates that a time is not on Saturday or Sunday.

func NotZeroTime

func NotZeroTime(v time.Time, field string) *Validation

NotZeroTime validates that a time is not the zero value.

func Numeric

func Numeric(v, field string) *Validation

Numeric validates that a string contains only ASCII digits.

func Odd

func Odd[T Integer](v T, field string) *Validation

Odd validates that an integer value is odd.

func OneOf

func OneOf(v string, allowed []string, field string) *Validation

OneOf validates that a string is one of the allowed values.

func OneOfValues

func OneOfValues[T comparable](v T, allowed []T, field string) *Validation

OneOfValues validates that a value is one of the allowed values.

func OnlyKeys

func OnlyKeys[K comparable, V any](v map[K]V, allowed []K, field string) *Validation

OnlyKeys validates that a map only contains keys from the allowed set.

func Percentage

func Percentage[T Number](v T, field string) *Validation

Percentage validates that a value is between 0 and 100.

func Port

func Port(v, field string) *Validation

Port validates that a string is a valid port number (1-65535).

func PortNumber

func PortNumber(v int, field string) *Validation

PortNumber validates that a value is a valid port number (1-65535).

func Positive

func Positive[T Signed | Float](v T, field string) *Validation

Positive validates that a value is greater than zero.

func Prefix

func Prefix(v, prefix, field string) *Validation

Prefix validates that a string starts with the given prefix.

func PrintableASCII

func PrintableASCII(v, field string) *Validation

PrintableASCII validates that a string contains only printable ASCII (32-126).

func Required

func Required(v, field string) *Validation

Required validates that a string is not empty (after trimming whitespace).

func RequiredPtr

func RequiredPtr[T any](v *T, fn func(T) *Validation, field string) *Validation

RequiredPtr validates that a pointer is not nil and applies validation to its value. Reports "required" validator, plus any validators from the inner function.

func RequiredPtrField

func RequiredPtrField[T any](v *T, fn func(T, string) *Validation, field string) *Validation

RequiredPtrField validates that a pointer is not nil and applies a field-aware validation.

func SameDay

func SameDay(v, ref time.Time, field string) *Validation

SameDay validates that a time is on the same day as the reference time.

func SameMonth

func SameMonth(v, ref time.Time, field string) *Validation

SameMonth validates that a time is in the same month as the reference time.

func SameYear

func SameYear(v, ref time.Time, field string) *Validation

SameYear validates that a time is in the same year as the reference time.

func Semver

func Semver(v, field string) *Validation

Semver validates that a string is a valid semantic version.

func SingleLine

func SingleLine(v, field string) *Validation

SingleLine validates that a string contains no newline characters.

func SliceContains

func SliceContains[T comparable](v []T, elem T, field string) *Validation

SliceContains validates that a slice contains the given element.

func SliceNotContains

func SliceNotContains[T comparable](v []T, elem T, field string) *Validation

SliceNotContains validates that a slice does not contain the given element.

func Slug

func Slug(v, field string) *Validation

Slug validates that a string is a valid URL slug (lowercase alphanumeric and hyphens).

func Subset

func Subset[T comparable](v, superset []T, field string) *Validation

Subset validates that all elements of v are in superset.

func Suffix

func Suffix(v, suffix, field string) *Validation

Suffix validates that a string ends with the given suffix.

func TimeInTimezone

func TimeInTimezone(v time.Time, loc *time.Location, field string) *Validation

TimeInTimezone validates that a time's location matches the expected timezone.

func Trimmed

func Trimmed(v, field string) *Validation

Trimmed validates that a string has no leading or trailing whitespace.

func URL

func URL(v, field string) *Validation

URL validates that a string is a valid URL.

func URLWithScheme

func URLWithScheme(v string, schemes []string, field string) *Validation

URLWithScheme validates that a string is a valid URL with one of the given schemes.

func UUID

func UUID(v, field string) *Validation

UUID validates that a string is a valid UUID (versions 1-5).

func UUID4

func UUID4(v, field string) *Validation

UUID4 validates that a string is a valid UUID version 4.

func Unique

func Unique[T comparable](v []T, field string) *Validation

Unique validates that all elements in a slice are unique.

func UniqueValues

func UniqueValues[K, V comparable](v map[K]V, field string) *Validation

UniqueValues validates that all values in a map are unique.

func UnixPath

func UnixPath(v, field string) *Validation

UnixPath validates that a string is a valid Unix-style path.

func UpperCase

func UpperCase(v, field string) *Validation

UpperCase validates that a string is entirely uppercase.

func Weekday

func Weekday(v time.Time, day time.Weekday, field string) *Validation

Weekday validates that a time is on the specified weekday.

func WeekdayIn

func WeekdayIn(v time.Time, days []time.Weekday, field string) *Validation

WeekdayIn validates that a time is on one of the specified weekdays.

func WithinDuration

func WithinDuration(v time.Time, d time.Duration, field string) *Validation

WithinDuration validates that a time is within a duration from now.

func WithinDurationOf

func WithinDurationOf(v time.Time, d time.Duration, ref time.Time, field string) *Validation

WithinDurationOf validates that a time is within a duration of a reference time.

func Zero

func Zero[T Number](v T, field string) *Validation

Zero validates that a value is exactly zero.

func ZeroTime

func ZeroTime(v time.Time, field string) *Validation

ZeroTime validates that a time is the zero value.

func (*Validation) Err

func (v *Validation) Err() error

Err returns the validation error (nil if validation passed).

func (*Validation) Error

func (v *Validation) Error() string

Error implements the error interface.

func (*Validation) Failed

func (v *Validation) Failed() bool

Failed returns true if the validation failed.

func (*Validation) Unwrap

func (v *Validation) Unwrap() error

Unwrap returns the underlying error for errors.Is/As compatibility.

Jump to

Keyboard shortcuts

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