validator

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 13 Imported by: 0

README

Validator Package

A comprehensive, type-safe validation library for Go applications with both simple functions and advanced generic validators.

Features

  • Type-safe generic validators for numbers, strings, and parsing
  • Composite validators with AND/OR logic and field matching
  • Collection validators for slices and maps
  • Integer-specific validators (even/odd, divisibility, powers, Fibonacci)
  • String validators (regex, character types, substring matching)
  • Date and duration parsing with custom formats
  • Custom validator builder for fluent chaining
  • Comprehensive test coverage

Quick Start

import "github.com/julianstephens/go-utils/validator"

// Simple validation
validator.ValidateNonEmpty("input")
validator.OneOf("active", "active", "inactive", "pending")

// Number validation
numValidator := validator.Numbers[int]()
numValidator.ValidateRange(42, 1, 100)

// String validation
strValidator := validator.Strings[string]()
strValidator.ValidateMinLength("hello", 3)
strValidator.Parse.ValidateEmail("[email protected]")

// Composite validation (AND/OR logic)
validator.All(
    func() error { return numValidator.ValidateRange(age, 18, 65) },
    func() error { return strValidator.ValidateMinLength(email, 5) },
)

// Field matching validation
validator.ValidateMatchesField(password, confirmPassword, "password")

// Custom validator builder
customVal := validator.NewCustomValidator().
    Add(func() error { return numValidator.ValidateRange(age, 18, 65) }).
    Add(func() error { return strValidator.ValidateMinLength(email, 5) })
if err := customVal.Validate(); err != nil {
    // handle error
}

// Collection validation
validator.ValidateSliceLength(items, 5)
validator.ValidateMapHasKey(config, "api_key")

API Reference

Factory Functions
  • Numbers[T]() *NumberValidator[T] - Create a number validator for type T
  • Strings[T]() *StringValidator[T] - Create a string validator for type T (includes Parse field for parsing validation)
  • Parse() *ParseValidator - Create a standalone parsing validator (advanced usage)
Number Validators

All number validators work with Number types: int, uint, float32, float64 and their variants.

Range Validation
  • ValidateMin(input T, min T) error - Value ≥ minimum
  • ValidateMax(input T, max T) error - Value ≤ maximum
  • ValidateRange(input T, min, max T) error - Value within range
Sign Validation
  • ValidatePositive(input T) error - Value > 0
  • ValidateNegative(input T) error - Value < 0
  • ValidateNonNegative(input T) error - Value ≥ 0
  • ValidateNonPositive(input T) error - Value ≤ 0
Equality Validation
  • ValidateZero(input T) error - Value == 0
  • ValidateNonZero(input T) error - Value != 0
  • ValidateEqual(input T, expected T) error - Value equals expected
  • ValidateNotEqual(input T, notExpected T) error - Value not equal
Comparison Validation
  • ValidateGreaterThan(input T, threshold T) error - Value > threshold
  • ValidateGreaterThanOrEqual(input T, threshold T) error - Value ≥ threshold
  • ValidateLessThan(input T, threshold T) error - Value < threshold
  • ValidateLessThanOrEqual(input T, threshold T) error - Value ≤ threshold
  • ValidateBetween(input T, lower, upper T) error - Value between bounds
  • ValidateConsecutive(input1, input2 T) error - input2 == input1 + 1
Integer-Only Validation
  • ValidateEven(input T) error - Value is even
  • ValidateOdd(input T) error - Value is odd
  • ValidateDivisibleBy(input T, divisor T) error - Evenly divisible
  • ValidatePowerOf(input T, base T) error - Power of base
  • ValidateFibonacci(input T) error - Is Fibonacci number
String Validators

String validators work with StringLike types: string, []byte, []rune.

Length Validation
  • ValidateMinLength(input T, min int) error - Length ≥ minimum
  • ValidateMaxLength(input T, max int) error - Length ≤ maximum
  • ValidateLengthRange(input T, min, max int) error - Length within range
Character Validation
  • ValidatePattern(input T, pattern string) error - Matches regex pattern
  • ValidateAlphanumeric(input T) error - Only alphanumeric
  • ValidateAlpha(input T) error - Only alphabetic
  • ValidateNumeric(input T) error - Only numeric
  • ValidateSlug(input T) error - Valid URL slug
  • ValidateLowercase(input T) error - Only lowercase
  • ValidateUppercase(input T) error - Only uppercase
Substring Validation
  • ValidateContains(input T, substring string) error - Contains substring
  • ValidateNotContains(input T, substring string) error - Doesn't contain substring
  • ValidatePrefix(input T, prefix string) error - Starts with prefix
  • ValidateSuffix(input T, suffix string) error - Ends with suffix
Parse Validators

Parsing validators for string format validation.

Format Validation
  • ValidateEmail(input string) error - Valid email format
  • ValidatePassword(input string) error - 8+ chars, mixed case, digits
  • ValidateUUID(input string) error - Valid UUID format
  • ValidateURL(input string) error - Valid URL format
  • ValidateDate(input string, format string) error - Valid date
  • ValidateDuration(input string) error - Valid duration (e.g., "5m", "2h")
  • ValidatePhoneNumber(input string) error - Valid phone format
Type Parsing
  • ValidateBool(input string) error - Parseable as bool
  • ValidateInt(input string) error - Parseable as int64
  • ValidateUint(input string) error - Parseable as uint64
  • ValidateFloat(input string) error - Parseable as float64
  • ValidatePositiveInt(input string) error - Parseable positive int
  • ValidateNonNegativeInt(input string) error - Parseable non-negative int
  • ValidatePositiveFloat(input string) error - Parseable positive float
Network Validation
  • ValidateIPAddress(input string) error - Valid IPv4 or IPv6 address
  • ValidateIPv4(input string) error - Valid IPv4 address
  • ValidateIPv6(input string) error - Valid IPv6 address
Composite Validators

Composite validators allow combining and chaining multiple validation functions.

Generic Validators
  • OneOf[T comparable](input T, allowed ...T) error - Value in allowed set
  • All(validators ...func() error) error - All pass (AND logic)
  • Any(validators ...func() error) error - At least one passes (OR logic)
  • ValidateMatchesField[T comparable](value1, value2 T, fieldName string) error - Two values match (e.g., password confirmation)
Collection Validators

Validators for slices, arrays, and maps.

Slice Validators
  • ValidateSliceLength[T any](input []T, length int) error - Length equals specified value
  • ValidateSliceMinLength[T any](input []T, min int) error - Length ≥ minimum
  • ValidateSliceMaxLength[T any](input []T, max int) error - Length ≤ maximum
  • ValidateSliceLengthRange[T any](input []T, min, max int) error - Length within range
  • ValidateSliceContains[T comparable](input []T, element T) error - Contains element
  • ValidateSliceNotContains[T comparable](input []T, element T) error - Doesn't contain element
  • ValidateSliceUnique[T comparable](input []T) error - All elements unique
Map Validators
  • ValidateMapHasKey[K comparable, V any](input map[K]V, key K) error - Contains key
  • ValidateMapNotHasKey[K comparable, V any](input map[K]V, key K) error - Doesn't contain key
  • ValidateMapMinLength[K comparable, V any](input map[K]V, min int) error - Entries ≥ minimum
  • ValidateMapMaxLength[K comparable, V any](input map[K]V, max int) error - Entries ≤ maximum
Utility Functions
  • ValidateNonEmpty[T](input T) error - Generic emptiness check for strings, bytes, runes, maps, and slices
  • NewCustomValidator() *CustomValidator - Create a custom validator with fluent chaining
  • Parse() *ParseValidator - Standalone parsing validator (typically accessed via StringValidator.Parse)
Custom Validator Builder

The CustomValidator type provides a fluent interface for composing validators:

cv := validator.NewCustomValidator().
    Add(func() error { return numVal.ValidateRange(age, 18, 65) }).
    Add(func() error { return strVal.ValidateMinLength(email, 5) }).
    Add(func() error { return strVal.ValidatePattern(phone, `^\+?[0-9\s\-\(\)]+$`) })

if err := cv.Validate(); err != nil {
    // All validators passed if no error
}

// For critical code paths, use SafeValidate() to recover from panics
if err := cv.SafeValidate(); err != nil {
    // Handle validation error or panic recovery
}
  • NewCustomValidator() *CustomValidator - Create a custom validator with fluent chaining
  • Add(validator func() error) *CustomValidator - Append a validator function
  • Validate() error - Run all validators in sequence (stops at first error)
  • SafeValidate() error - Run all validators with panic recovery

Type Constraints

The package uses Go generics with these type constraints:

  • Number: ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
  • StringLike: ~string | ~[]byte | ~[]rune
  • Emptyable: ~string | ~[]byte | ~[]rune | ~map[string]interface{} | ~[]interface{}

Error Handling

All validators return *ValidationError with detailed context:

if err := numValidator.ValidateRange(-5, 0, 100); err != nil {
    var valErr *validator.ValidationError
    if errors.As(err, &valErr) {
        fmt.Printf("Validation failed: %s (expected: %v, got: %v)",
            valErr.Cause, valErr.Want, valErr.Have)
    }
}

Examples

User Registration Validation
func validateUser(name, email, ageStr string) error {
    // String validation
    strVal := validator.Strings[string]()
    if err := strVal.ValidateMinLength(name, 2); err != nil {
        return fmt.Errorf("name validation: %w", err)
    }

    // Parse validation (accessed through string validator)
    if err := strVal.Parse.ValidateEmail(email); err != nil {
        return fmt.Errorf("email validation: %w", err)
    }

    // Number validation after parsing
    age, err := strconv.Atoi(ageStr)
    if err != nil {
        return fmt.Errorf("age parsing: %w", err)
    }

    numVal := validator.Numbers[int]()
    if err := numVal.ValidateRange(age, 13, 120); err != nil {
        return fmt.Errorf("age validation: %w", err)
    }

    return nil
}
Configuration Validation
func validateConfig(port int, host string, timeout float64) error {
    // Port validation
    portVal := validator.Numbers[int]()
    if err := portVal.ValidateRange(port, 1024, 65535); err != nil {
        return fmt.Errorf("invalid port: %w", err)
    }

    // Host validation
    hostVal := validator.Strings[string]()
    if err := hostVal.ValidateMinLength(host, 1); err != nil {
        return fmt.Errorf("invalid host: %w", err)
    }

    // Timeout validation
    timeoutVal := validator.Numbers[float64]()
    if err := timeoutVal.ValidateRange(timeout, 0.1, 300.0); err != nil {
        return fmt.Errorf("invalid timeout: %w", err)
    }

    return nil
}
Safe Validation with Panic Recovery
// Use SafeValidate() to prevent validation panics from crashing the application
cv := validator.NewCustomValidator().
    Add(func() error { return numVal.ValidateRange(age, 18, 65) }).
    Add(func() error { return strVal.ValidateMinLength(email, 5) })

// SafeValidate recovers from panics and returns error instead
if err := cv.SafeValidate(); err != nil {
    // Handle validation error (may be from panic recovery)
    log.Printf("Validation failed: %v", err)
}

Performance

Efficiency

The validator package is designed for performance:

  • Zero Allocations for most validators (numbers, basic strings)
  • Lazy Validation - stops at first error in composite validators
  • Minimal Overhead - generic validators compile to native code
  • Type-Safe - no runtime type assertions for generics
Benchmarks

Typical performance characteristics (on modern hardware):

  • Number validation (range): ~10-50 ns/op
  • String validation (length): ~20-100 ns/op
  • Pattern validation (regex): ~200-1000 ns/op
  • Composite validation (3 validators): ~30-150 ns/op
Performance Tips
  1. Prefer simple validators over regex for basic patterns
  2. Order validators by cost - cheap checks before expensive ones
  3. Reuse validators - create once, use many times
  4. Use composite validators rather than nested if statements
  5. Profile first - use benchmarks to identify bottlenecks

Example optimization:

// Good: cheap validation first
cv := validator.NewCustomValidator().
    Add(func() error { return strVal.ValidateMinLength(email, 5) }).   // ~30 ns
    Add(func() error { return strVal.Parse.ValidateEmail(email) })     // ~500 ns

// Less ideal: expensive validation first  
cv := validator.NewCustomValidator().
    Add(func() error { return strVal.Parse.ValidateEmail(email) }).    // ~500 ns
    Add(func() error { return strVal.ValidateMinLength(email, 5) })    // ~30 ns (never reached if email invalid)

Testing

go test -v ./validator
go test -cover ./validator

Documentation

Overview

Package validator provides comprehensive, reusable input validators for Go applications.

The package offers both simple validation functions and advanced generic validators for type-safe validation of numbers, strings, and parsed values. Validators are designed to be composable and reusable across different parts of an application.

Basic Usage

Simple validation functions for common checks:

import "github.com/julianstephens/go-utils/validator"

if err := validator.ValidateNonEmpty("input"); err != nil {
    // handle empty input
}

Advanced Generic Validators

For comprehensive validation, use the generic validator factories:

// Number validation
numValidator := validator.Numbers[int]()
if err := numValidator.ValidateRange(42, 1, 100); err != nil {
    // handle invalid number
}

// String validation
strValidator := validator.Strings[string]()
if err := strValidator.ValidateMinLength("hello", 3); err != nil {
    // handle string too short
}

// Parsing validation (accessed through string validator)
strValidator := validator.Strings[string]()
if err := strValidator.Parse.ValidateEmail("[email protected]"); err != nil {
    // handle invalid email
}

Type Constraints

The package uses Go generics with type constraints:

  • Number: ~int, ~uint, ~float32, ~float64 variants
  • StringLike: ~string, ~[]byte, ~[]rune
  • Emptyable: types that can be checked for emptiness

Error Handling

All validators return detailed ValidationError instances with context about what was expected vs. what was received, making debugging easier.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyInput = fmt.Errorf("input cannot be empty")

	ErrInvalidInput  = fmt.Errorf("invalid input")
	ErrInvalidFormat = fmt.Errorf("invalid format")

	ErrTooShort = fmt.Errorf("input is too short")
	ErrTooLong  = fmt.Errorf("input is too long")

	ErrMissingUppercase   = fmt.Errorf("missing uppercase letter")
	ErrMissingLowercase   = fmt.Errorf("missing lowercase letter")
	ErrMissingDigit       = fmt.Errorf("missing digit")
	ErrMissingSpecialChar = fmt.Errorf("missing special character")

	ErrStringTooShort         = fmt.Errorf("string is too short")
	ErrStringTooLong          = fmt.Errorf("string is too long")
	ErrStringLengthOutOfRange = fmt.Errorf("string length out of range")
	ErrInvalidPattern         = fmt.Errorf("string does not match pattern")
	ErrNotAlphanumeric        = fmt.Errorf("string contains non-alphanumeric characters")
	ErrNotAlpha               = fmt.Errorf("string contains non-alphabetic characters")
	ErrNotNumeric             = fmt.Errorf("string contains non-numeric characters")
	ErrInvalidSlug            = fmt.Errorf("string is not a valid slug")
	ErrNotLowercase           = fmt.Errorf("string contains uppercase characters")
	ErrNotUppercase           = fmt.Errorf("string contains lowercase characters")
	ErrNotContains            = fmt.Errorf("string does not contain substring")
	ErrContains               = fmt.Errorf("string contains substring")
	ErrInvalidPrefix          = fmt.Errorf("string does not have expected prefix")
	ErrInvalidSuffix          = fmt.Errorf("string does not have expected suffix")

	ErrInvalidInteger   = fmt.Errorf("invalid integer")
	ErrInvalidFloat     = fmt.Errorf("invalid float")
	ErrInvalidBoolean   = fmt.Errorf("invalid boolean")
	ErrInvalidUUID      = fmt.Errorf("invalid UUID")
	ErrInvalidEmail     = fmt.Errorf("invalid email")
	ErrInvalidURL       = fmt.Errorf("invalid URL")
	ErrInvalidIPAddress = fmt.Errorf("invalid IP address")
	ErrInvalidIPv4      = fmt.Errorf("invalid IPv4 address")
	ErrInvalidIPv6      = fmt.Errorf("invalid IPv6 address")
	ErrInvalidDate      = fmt.Errorf("invalid date")
	ErrInvalidDuration  = fmt.Errorf("invalid duration")
	ErrInvalidPhone     = fmt.Errorf("invalid phone number")
	ErrNotInSet         = fmt.Errorf("value not in allowed set")
	ErrSliceTooShort    = fmt.Errorf("slice is too short")
	ErrSliceTooLong     = fmt.Errorf("slice is too long")
	ErrFieldMismatch    = fmt.Errorf("field values do not match")

	ErrNumberTooSmall   = fmt.Errorf("number is too small")
	ErrNumberTooLarge   = fmt.Errorf("number is too large")
	ErrNotPositive      = fmt.Errorf("number is not positive")
	ErrNotNegative      = fmt.Errorf("number is not negative")
	ErrNotZero          = fmt.Errorf("number is not zero")
	ErrNumberOutOfRange = fmt.Errorf("number out of range")
	ErrNotEqual         = fmt.Errorf("number not equal")
	ErrNumberZero       = fmt.Errorf("number is zero")
	ErrNumberPositive   = fmt.Errorf("number is positive")
	ErrNumberNegative   = fmt.Errorf("number is negative")
	ErrNotGreaterThan   = fmt.Errorf("number not greater than threshold")
	ErrNotLessThan      = fmt.Errorf("number not less than threshold")

	ErrUnsupportedType = fmt.Errorf("unsupported type")
)

Functions

func All added in v0.3.1

func All(validators ...func() error) error

All validates that all validator functions pass (AND logic)

func Any added in v0.3.1

func Any(validators ...func() error) error

Any validates that at least one validator function passes (OR logic)

func OneOf added in v0.3.1

func OneOf[T comparable](input T, allowed ...T) error

OneOf validates that a value is one of the allowed values

func ValidateMapHasKey added in v0.3.1

func ValidateMapHasKey[K comparable, V any](input map[K]V, key K) error

ValidateMapHasKey validates that a map contains the specified key

func ValidateMapMaxLength added in v0.3.1

func ValidateMapMaxLength[K comparable, V any](input map[K]V, max int) error

ValidateMapMaxLength validates that a map has at most the maximum number of entries

func ValidateMapMinLength added in v0.3.1

func ValidateMapMinLength[K comparable, V any](input map[K]V, min int) error

ValidateMapMinLength validates that a map has at least the minimum number of entries

func ValidateMapNotHasKey added in v0.3.1

func ValidateMapNotHasKey[K comparable, V any](input map[K]V, key K) error

ValidateMapNotHasKey validates that a map does not contain the specified key

func ValidateMatchesField added in v0.3.1

func ValidateMatchesField[T comparable](value1 T, value2 T, fieldName string) error

ValidateMatchesField validates that two comparable values are equal (useful for password confirmation)

func ValidateNonEmpty

func ValidateNonEmpty[T Emptyable](input T) error

ValidateNonEmpty validates that input is not empty

func ValidateSliceContains added in v0.3.1

func ValidateSliceContains[T comparable](input []T, element T) error

ValidateSliceContains validates that a slice contains the specified element

func ValidateSliceLength added in v0.3.1

func ValidateSliceLength[T any](input []T, length int) error

ValidateSliceLength validates that a slice has the specified length

func ValidateSliceLengthRange added in v0.3.1

func ValidateSliceLengthRange[T any](input []T, min, max int) error

ValidateSliceLengthRange validates that a slice length is within the specified range (inclusive)

func ValidateSliceMaxLength added in v0.3.1

func ValidateSliceMaxLength[T any](input []T, max int) error

ValidateSliceMaxLength validates that a slice has at most the maximum length

func ValidateSliceMinLength added in v0.3.1

func ValidateSliceMinLength[T any](input []T, min int) error

ValidateSliceMinLength validates that a slice has at least the minimum length

func ValidateSliceNotContains added in v0.3.1

func ValidateSliceNotContains[T comparable](input []T, element T) error

ValidateSliceNotContains validates that a slice does not contain the specified element

func ValidateSliceUnique added in v0.3.1

func ValidateSliceUnique[T comparable](input []T) error

ValidateSliceUnique validates that all elements in a slice are unique

Types

type CustomValidator added in v0.3.1

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

CustomValidator provides a builder pattern for composing multiple validators

func NewCustomValidator added in v0.3.1

func NewCustomValidator() *CustomValidator

NewCustomValidator creates a new CustomValidator instance

func (*CustomValidator) Add added in v0.3.1

func (cv *CustomValidator) Add(validator func() error) *CustomValidator

Add appends a validator function to the custom validator

func (*CustomValidator) SafeValidate added in v0.4.2

func (cv *CustomValidator) SafeValidate() (returnErr error)

SafeValidate runs all accumulated validators in sequence with panic recovery. If any validator panics, the panic is recovered and logged to stderr. This prevents validation errors from crashing the application. Use in critical paths where you want validation to fail gracefully.

func (*CustomValidator) Validate added in v0.3.1

func (cv *CustomValidator) Validate() error

Validate runs all accumulated validators in sequence (AND logic)

type Emptyable added in v0.3.0

type Emptyable interface {
	~string | ~[]byte | ~[]rune | ~map[string]interface{} | ~[]interface{}
}

type Integer added in v0.3.1

type Integer interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

Type constraints

type Number added in v0.3.0

type Number interface {
	Integer | ~float32 | ~float64
}

type NumberValidator added in v0.3.0

type NumberValidator[T Number] struct{}

func Numbers added in v0.3.0

func Numbers[T Number]() *NumberValidator[T]

Numbers returns a NumberValidator for the specified numeric type.

func (*NumberValidator[T]) Errorf added in v0.3.0

func (nv *NumberValidator[T]) Errorf(cause string, want, have any, err error) *ValidationError

func (*NumberValidator[T]) ValidateBetween added in v0.3.0

func (nv *NumberValidator[T]) ValidateBetween(input T, lower T, upper T) error

ValidateBetween validates that a number is within the specified bounds (inclusive)

func (*NumberValidator[T]) ValidateConsecutive added in v0.3.1

func (nv *NumberValidator[T]) ValidateConsecutive(input1, input2 T) error

ValidateConsecutive validates that the second number is exactly one greater than the first

func (*NumberValidator[T]) ValidateDivisibleBy added in v0.3.1

func (nv *NumberValidator[T]) ValidateDivisibleBy(input T, divisor T) error

ValidateDivisibleBy validates that a number is evenly divisible by the divisor (integer types only)

func (*NumberValidator[T]) ValidateEqual added in v0.3.0

func (nv *NumberValidator[T]) ValidateEqual(input T, expected T) error

ValidateEqual validates that a number equals the expected value

func (*NumberValidator[T]) ValidateEven added in v0.3.1

func (nv *NumberValidator[T]) ValidateEven(input T) error

ValidateEven validates that a number is even (integer types only)

func (*NumberValidator[T]) ValidateFibonacci added in v0.3.1

func (nv *NumberValidator[T]) ValidateFibonacci(input T) error

ValidateFibonacci validates that a number is a Fibonacci number (integer types only)

func (*NumberValidator[T]) ValidateGreaterThan added in v0.3.0

func (nv *NumberValidator[T]) ValidateGreaterThan(input T, threshold T) error

ValidateGreaterThan validates that a number is strictly greater than the threshold

func (*NumberValidator[T]) ValidateGreaterThanOrEqual added in v0.3.0

func (nv *NumberValidator[T]) ValidateGreaterThanOrEqual(input T, threshold T) error

ValidateGreaterThanOrEqual validates that a number is greater than or equal to the threshold

func (*NumberValidator[T]) ValidateLessThan added in v0.3.0

func (nv *NumberValidator[T]) ValidateLessThan(input T, threshold T) error

ValidateLessThan validates that a number is strictly less than the threshold

func (*NumberValidator[T]) ValidateLessThanOrEqual added in v0.3.0

func (nv *NumberValidator[T]) ValidateLessThanOrEqual(input T, threshold T) error

ValidateLessThanOrEqual validates that a number is less than or equal to the threshold

func (*NumberValidator[T]) ValidateMax added in v0.3.0

func (nv *NumberValidator[T]) ValidateMax(input T, max T) error

ValidateMax validates that a number is less than or equal to the maximum value

func (*NumberValidator[T]) ValidateMin added in v0.3.0

func (nv *NumberValidator[T]) ValidateMin(input T, min T) error

ValidateMin validates that a number is greater than or equal to the minimum value

func (*NumberValidator[T]) ValidateNegative added in v0.3.0

func (nv *NumberValidator[T]) ValidateNegative(input T) error

ValidateNegative validates that a number is less than zero

func (*NumberValidator[T]) ValidateNonNegative added in v0.3.0

func (nv *NumberValidator[T]) ValidateNonNegative(input T) error

ValidateNonNegative validates that a number is greater than or equal to zero

func (*NumberValidator[T]) ValidateNonPositive added in v0.3.0

func (nv *NumberValidator[T]) ValidateNonPositive(input T) error

ValidateNonPositive validates that a number is less than or equal to zero

func (*NumberValidator[T]) ValidateNonZero added in v0.3.0

func (nv *NumberValidator[T]) ValidateNonZero(input T) error

ValidateNonZero validates that a number is not equal to zero

func (*NumberValidator[T]) ValidateNotEqual added in v0.3.0

func (nv *NumberValidator[T]) ValidateNotEqual(input T, notExpected T) error

ValidateNotEqual validates that a number is not equal to the specified value

func (*NumberValidator[T]) ValidateOdd added in v0.3.1

func (nv *NumberValidator[T]) ValidateOdd(input T) error

ValidateOdd validates that a number is odd (integer types only)

func (*NumberValidator[T]) ValidatePositive added in v0.3.0

func (nv *NumberValidator[T]) ValidatePositive(input T) error

ValidatePositive validates that a number is greater than zero

func (*NumberValidator[T]) ValidatePowerOf added in v0.3.1

func (nv *NumberValidator[T]) ValidatePowerOf(input T, base T) error

ValidatePowerOf validates that a number is a power of the specified base (integer types only)

func (*NumberValidator[T]) ValidateRange added in v0.3.0

func (nv *NumberValidator[T]) ValidateRange(input T, min, max T) error

ValidateRange validates that a number is within the specified range (inclusive)

func (*NumberValidator[T]) ValidateZero added in v0.3.0

func (nv *NumberValidator[T]) ValidateZero(input T) error

ValidateZero validates that a number equals zero

type ParseValidator added in v0.3.0

type ParseValidator struct{}

func Parse added in v0.3.0

func Parse() *ParseValidator

Parse returns a ParseValidator for parsing string inputs.

func (*ParseValidator) Errorf added in v0.3.0

func (pv *ParseValidator) Errorf(cause string, want, have any, err error) error

func (*ParseValidator) ValidateBool added in v0.3.0

func (pv *ParseValidator) ValidateBool(input string) error

ValidateBool validates that input can be parsed as a boolean

func (*ParseValidator) ValidateDate added in v0.3.1

func (pv *ParseValidator) ValidateDate(input string, format string) error

ValidateDate validates that input can be parsed as a date in the specified format

func (*ParseValidator) ValidateDuration added in v0.3.1

func (pv *ParseValidator) ValidateDuration(input string) error

ValidateDuration validates that input can be parsed as a duration (e.g., "5m", "2h", "1s")

func (*ParseValidator) ValidateEmail added in v0.3.0

func (pv *ParseValidator) ValidateEmail(input string) error

func (*ParseValidator) ValidateFloat added in v0.3.0

func (pv *ParseValidator) ValidateFloat(input string) error

ValidateFloat validates that input can be parsed as a float

func (*ParseValidator) ValidateIPAddress added in v0.3.0

func (pv *ParseValidator) ValidateIPAddress(input string) error

ValidateIPAddress validates that input is a valid IP address (IPv4 or IPv6)

func (*ParseValidator) ValidateIPv4 added in v0.3.0

func (pv *ParseValidator) ValidateIPv4(input string) error

ValidateIPv4 validates that input is a valid IPv4 address

func (*ParseValidator) ValidateIPv6 added in v0.3.0

func (pv *ParseValidator) ValidateIPv6(input string) error

ValidateIPv6 validates that input is a valid IPv6 address

func (*ParseValidator) ValidateInt added in v0.3.0

func (pv *ParseValidator) ValidateInt(input string) error

ValidateInt validates that input can be parsed as an integer

func (*ParseValidator) ValidateNonNegativeInt added in v0.3.0

func (pv *ParseValidator) ValidateNonNegativeInt(input string) error

ValidateNonNegativeInt validates that input is a non-negative integer

func (*ParseValidator) ValidatePassword added in v0.3.0

func (pv *ParseValidator) ValidatePassword(input string) error

func (*ParseValidator) ValidatePhoneNumber added in v0.3.1

func (pv *ParseValidator) ValidatePhoneNumber(input string) error

ValidatePhoneNumber validates that input is a valid phone number (basic format: digits, spaces, hyphens, +)

func (*ParseValidator) ValidatePositiveFloat added in v0.3.0

func (pv *ParseValidator) ValidatePositiveFloat(input string) error

ValidatePositiveFloat validates that input is a positive float

func (*ParseValidator) ValidatePositiveInt added in v0.3.0

func (pv *ParseValidator) ValidatePositiveInt(input string) error

ValidatePositiveInt validates that input is a positive integer

func (*ParseValidator) ValidateURL added in v0.3.0

func (pv *ParseValidator) ValidateURL(input string) error

ValidateURL validates that input is a valid URL

func (*ParseValidator) ValidateUUID added in v0.3.0

func (pv *ParseValidator) ValidateUUID(input string) error

func (*ParseValidator) ValidateUint added in v0.3.0

func (pv *ParseValidator) ValidateUint(input string) error

ValidateUint validates that input can be parsed as an unsigned integer

type StringLike added in v0.3.0

type StringLike interface {
	~string | ~[]byte | ~[]rune
}

type StringValidator added in v0.3.0

type StringValidator[T StringLike] struct {
	Parse *ParseValidator
}

func Strings added in v0.3.0

func Strings[T StringLike]() *StringValidator[T]

Strings returns a StringValidator for the specified string-like type.

func (*StringValidator[T]) Errorf added in v0.3.0

func (sv *StringValidator[T]) Errorf(cause string, want, have any, err error) *ValidationError

func (*StringValidator[T]) ValidateAlpha added in v0.3.1

func (sv *StringValidator[T]) ValidateAlpha(input T) error

ValidateAlpha validates that a string contains only alphabetic characters

func (*StringValidator[T]) ValidateAlphanumeric added in v0.3.1

func (sv *StringValidator[T]) ValidateAlphanumeric(input T) error

ValidateAlphanumeric validates that a string contains only alphanumeric characters

func (*StringValidator[T]) ValidateContains added in v0.3.1

func (sv *StringValidator[T]) ValidateContains(input T, substring string) error

ValidateContains validates that a string contains the specified substring

func (*StringValidator[T]) ValidateLengthRange added in v0.3.0

func (sv *StringValidator[T]) ValidateLengthRange(input T, min, max int) error

ValidateLengthRange validates that a string length is within the specified range (inclusive)

func (*StringValidator[T]) ValidateLowercase added in v0.3.1

func (sv *StringValidator[T]) ValidateLowercase(input T) error

ValidateLowercase validates that a string contains only lowercase characters (letters only)

func (*StringValidator[T]) ValidateMaxLength added in v0.3.0

func (sv *StringValidator[T]) ValidateMaxLength(input T, max int) error

ValidateMaxLength validates that a string is at most the maximum length

func (*StringValidator[T]) ValidateMinLength added in v0.3.0

func (sv *StringValidator[T]) ValidateMinLength(input T, min int) error

ValidateMinLength validates that a string is at least the minimum length

func (*StringValidator[T]) ValidateNotContains added in v0.3.1

func (sv *StringValidator[T]) ValidateNotContains(input T, substring string) error

ValidateNotContains validates that a string does not contain the specified substring

func (*StringValidator[T]) ValidateNumeric added in v0.3.1

func (sv *StringValidator[T]) ValidateNumeric(input T) error

ValidateNumeric validates that a string contains only numeric characters

func (*StringValidator[T]) ValidatePattern added in v0.3.1

func (sv *StringValidator[T]) ValidatePattern(input T, pattern string) error

ValidatePattern validates that a string matches the specified regex pattern

func (*StringValidator[T]) ValidatePrefix added in v0.3.1

func (sv *StringValidator[T]) ValidatePrefix(input T, prefix string) error

ValidatePrefix validates that a string starts with the specified prefix

func (*StringValidator[T]) ValidateSlug added in v0.3.1

func (sv *StringValidator[T]) ValidateSlug(input T) error

ValidateSlug validates that a string is a valid URL slug (lowercase alphanumeric with hyphens and underscores)

func (*StringValidator[T]) ValidateSuffix added in v0.3.1

func (sv *StringValidator[T]) ValidateSuffix(input T, suffix string) error

ValidateSuffix validates that a string ends with the specified suffix

func (*StringValidator[T]) ValidateUppercase added in v0.3.1

func (sv *StringValidator[T]) ValidateUppercase(input T) error

ValidateUppercase validates that a string contains only uppercase characters (letters only)

type ValidationError added in v0.3.0

type ValidationError struct {
	Module ValidationModule
	Cause  string
	Want   any
	Have   any
	Err    error
}

func NewValidationError added in v0.3.0

func NewValidationError(module ValidationModule, cause string, want, have any, err error) *ValidationError

func (*ValidationError) Error added in v0.3.0

func (ve *ValidationError) Error() string

type ValidationModule added in v0.3.0

type ValidationModule int
const (
	ModuleUnknown ValidationModule = iota
	ModuleParse
	ModuleString
	ModuleNumber
)

Jump to

Keyboard shortcuts

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