types

package module
v0.0.0-...-72cce92 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 12 Imported by: 3

README

go-types

A comprehensive Go library providing enhanced type definitions, validation, and utility functions for common data types and operations.

Overview

go-types is a collection of Go packages that extend the standard library with additional type definitions, validation frameworks, and utility functions. It provides type-safe implementations for common data structures and operations, making it easier to work with validated data, nullable types, and specialized data formats.

Features

  • Type-Safe Collections: Generic Set implementation with comprehensive operations
  • Validation Framework: Flexible validation system with both boolean and error-based validation
  • Nullable Types: Support for nullable values with proper JSON marshaling/unmarshaling
  • Specialized Data Types: Email addresses, dates, money amounts, VAT IDs, and more
  • String Utilities: Enhanced string manipulation and formatting functions
  • Iterator Utilities: Helper functions for Go's iterator patterns
  • JSON Support: Comprehensive JSON marshaling/unmarshaling for all types

Core Packages

Main Package (types)

The main package provides core utilities and type definitions:

Collections
  • Set[T]: A generic set implementation with comprehensive operations (union, intersection, difference, etc.)
  • Slice Utilities: Functions for checking slice containment (SliceContainsAll, SliceContainsAny)
Validation Framework
  • Validator: Interface for boolean validation
  • ValidatErr: Interface for validation with detailed error information
  • DeepValidate: Recursive validation of nested structures
  • CombinedValidator: Combine multiple validators
Utility Functions
  • Pointer Utilities: Safe pointer dereferencing (Ptr, FromPtr, FromPtrOr)
  • Iterator Helpers: Functions for working with Go's iterator patterns (Yield, Yield2, YieldErr)
  • JSON Utilities: Check if types can be marshaled as JSON (CanMarshalJSON)
Specialized Types
  • LenString: String with length constraints and validation
  • Finder: Interface for pattern matching in byte slices
Subpackages
email - Email Address Handling
  • Address: Email address type with normalization and validation
  • AddressList: Collection of email addresses
  • AddressSet: Set of unique email addresses
  • Attachment: Email attachment handling
  • Message: Complete email message structure
  • ParseAddress: Flexible email address parsing
money - Financial Data Types
  • Amount: Money amount with decimal precision handling
  • Currency: Currency codes and information
  • CurrencyAmount: Combined currency and amount
  • Rate: Exchange rate handling
  • AmountParser: Parse monetary values from strings
  • CurrencyParser: Parse currency information
date - Date Handling
  • Date: Date type with comprehensive parsing and formatting
  • NullableDate: Nullable date type
  • DateNames: Localized date names
  • DateFinder: Find dates in text
  • DateFormatter: Format dates in various styles
  • DateParser: Parse dates from strings
bank - Banking Data Types
  • IBAN: International Bank Account Number handling
  • BIC: Bank Identifier Code handling
  • Account: Bank account information
  • CAMT53: ISO 20022 CAMT.053 message handling
  • IBANParser/BICParser: Parse banking identifiers
vat - VAT ID Handling
  • ID: VAT identification number with country-specific validation
  • IDFinder: Find VAT IDs in text
  • IDParser: Parse VAT IDs from strings
  • NullableID: Nullable VAT ID type
country - Country Information
  • Code: ISO country codes
  • NullableCode: Nullable country code
  • Country Data: Comprehensive country information
language - Language Codes
  • Code: ISO 639 language codes
  • Constants: Language code constants
  • ISO6393: ISO 639-3 language names
nullable - Nullable Types
  • Type[T]: Generic nullable type wrapper
  • Arrays: Nullable array types for various data types
  • NonEmptyString: String that cannot be empty
  • TrimmedString: String with automatic trimming
  • Time: Nullable time type
strutil - String Utilities
  • String Manipulation: Enhanced string functions
  • DomainName: Domain name validation and manipulation
  • HTML Utilities: HTML processing functions
  • Random: Random string generation
  • StringSet: Set of strings
  • StrMutex: String-based mutex for synchronization
strfmt - String Formatting
  • Format: String format detection and handling
  • Scanner: String scanning utilities
  • Formatter: String formatting functions
  • Detector: Format detection algorithms
float - Float Utilities
  • Parse: Enhanced float parsing with tolerance
  • Format: Float formatting utilities
  • Tolerant: Tolerant float operations
queue - Queue Implementation
  • Queue: Generic queue interface and implementation
  • RingBuffer: Ring buffer for efficient queue operations
charset - Character Set Handling
  • Encoding: Character encoding detection and conversion
  • UTF8/UTF16/UTF32: Unicode handling utilities
  • BOM: Byte Order Mark handling
uu - UUID Utilities
  • ID: UUID handling and generation
  • IDContext: Context-aware UUID operations
  • IDMutex: UUID-based mutex for synchronization
  • IDSet: Set of UUIDs
  • IDSlice: Slice of UUIDs with utilities

Installation

go get github.com/domonda/go-types

Usage Examples

Sets
package main

import (
    "fmt"
    "github.com/domonda/go-types"
)

func main() {
    // Create a set
    set1 := types.NewSet(1, 2, 3, 4, 5)
    set2 := types.NewSet(4, 5, 6, 7, 8)
    
    // Set operations
    union := set1.Union(set2)
    intersection := set1.Intersection(set2)
    difference := set1.Difference(set2)
    
    fmt.Printf("Union: %v\n", union.Sorted())
    fmt.Printf("Intersection: %v\n", intersection.Sorted())
    fmt.Printf("Difference: %v\n", difference.Sorted())
}
Validation
package main

import (
    "fmt"
    "github.com/domonda/go-types"
)

type User struct {
    Name  string
    Email string
    Age   int
}

func (u User) Validate() error {
    if u.Name == "" {
        return fmt.Errorf("name is required")
    }
    if u.Age < 0 {
        return fmt.Errorf("age must be non-negative")
    }
    return nil
}

func main() {
    user := User{Name: "John", Email: "[email protected]", Age: 25}
    
    // Validate single value
    if err := types.Validate(user); err != nil {
        fmt.Printf("Validation error: %v\n", err)
    }
    
    // Deep validation of nested structures
    if err := types.DeepValidate(user); err != nil {
        fmt.Printf("Deep validation error: %v\n", err)
    }
}
Email Addresses
package main

import (
    "fmt"
    "github.com/domonda/go-types/email"
)

func main() {
    // Parse and normalize email address
    addr, err := email.NormalizedAddress("John Doe <[email protected]>")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Normalized: %s\n", addr)
    
    // Create address list
    list := email.AddressList{addr, email.Address("[email protected]")}
    fmt.Printf("Address list: %v\n", list)
}
Money Amounts
package main

import (
    "fmt"
    "github.com/domonda/go-types/money"
)

func main() {
    // Parse money amount
    amount, err := money.ParseAmount("123.45", 2) // 2 decimal places
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Amount: %v\n", amount)
    
    // Create currency amount
    currencyAmount := money.CurrencyAmount{
        Amount:   amount,
        Currency: money.Currency("USD"),
    }
    
    fmt.Printf("Currency amount: %v\n", currencyAmount)
}
Dates
package main

import (
    "fmt"
    "github.com/domonda/go-types/date"
)

func main() {
    // Parse date from string
    d, err := date.Normalize("2024-01-15")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Date: %s\n", d)
    fmt.Printf("Is valid: %v\n", d.Valid())
}
Nullable Types
package main

import (
    "fmt"
    "github.com/domonda/go-types/nullable"
)

func main() {
    // Create nullable string
    nullableStr := nullable.New("hello")
    
    fmt.Printf("Value: %v\n", nullableStr.Value())
    fmt.Printf("Is null: %v\n", nullableStr.IsNull())
    
    // Set to null
    nullableStr.SetNull()
    fmt.Printf("Is null after SetNull: %v\n", nullableStr.IsNull())
}

JSON Support

All types in go-types support JSON marshaling and unmarshaling:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/domonda/go-types"
)

func main() {
    // Set JSON marshaling
    set := types.NewSet(1, 2, 3, 4, 5)
    
    jsonData, err := json.Marshal(set)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("JSON: %s\n", string(jsonData))
    
    // Unmarshal back to set
    var newSet types.Set[int]
    err = json.Unmarshal(jsonData, &newSet)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Unmarshaled set: %v\n", newSet.Sorted())
}

Testing

The library includes comprehensive tests for all functionality:

go test ./...

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Dependencies

  • Go 1.24.0 or later
  • Standard library packages
  • External dependencies are minimal and well-maintained

Performance

The library is designed with performance in mind:

  • Generic types provide compile-time type safety
  • Efficient data structures (sets implemented as maps)
  • Minimal allocations where possible
  • Comprehensive caching for expensive operations

Security

Security considerations:

  • Input validation for all user-provided data
  • Safe handling of nullable types
  • Proper error handling and reporting
  • No unsafe operations exposed in public API

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidValue = errors.New("invalid value")

ErrInvalidValue means that a value is not valid, returned by Validate() and ValidatorAsValidatErr.Validate().

Functions

func CanMarshalJSON

func CanMarshalJSON(t reflect.Type) bool

CanMarshalJSON returns true if a type can be marshalled as JSON. It checks if the type implements json.Marshaler or encoding.TextMarshaler, or if it's a struct, map, or slice that can be marshalled by the standard JSON package.

func DeepValidate

func DeepValidate(v any) []error

DeepValidate recursively validates all fields of a struct, all elements of a slice or array, and all values of a map by recursively calling Validate or Valid methods. It returns all validation errors as a slice. Use errors.Join(DeepValidate(v)...) to join the errors into a single error.

func FromPtr

func FromPtr[T any](ptr *T) T

FromPtr returns the dereferenced value of the pointer if it is not nil, otherwise it returns the zero value of the type T. This safely dereferences a pointer without panicking on nil.

func FromPtrOr

func FromPtrOr[T any](ptr *T, defaultValue T) T

FromPtrOr returns the dereferenced value of the pointer if it is not nil, otherwise it returns the passed defaultValue. This provides a safe way to dereference a pointer with a fallback value.

func Ptr

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

Ptr returns a new pointer to a copy of the passed value. This is useful for creating pointers to values that need to be passed by reference.

func ReduceSet

func ReduceSet[S ~map[T]struct{}, T cmp.Ordered, R any](set S, reduceFunc func(last R, val T) R) (result R)

ReduceSet applies a reduction function to all values in the set and returns the result. The reduceFunc is called for each value in the set, with the accumulated result and the current value.

func ReduceSlice

func ReduceSlice[S ~[]T, T cmp.Ordered, R any](slice S, reduceFunc func(last R, val T) R) (result R)

ReduceSlice applies a reduction function to all values in the slice and returns the result. The reduceFunc is called for each value in the slice, with the accumulated result and the current value.

func ReflectCompare

func ReflectCompare(a, b reflect.Value) int

ReflectCompare compares two reflect.Values of the same type. The function panics if the types of a and b are not idential or not orderable. Orderable types are variantes of integers, floats, and strings. This is used for sorting map keys in DeepValidate.

func Seq2NilError

func Seq2NilError[K any](seq iter.Seq[K]) iter.Seq2[K, error]

Seq2NilError converts a sequence of values to a sequence of key-value pairs with the passed sequence values as keys and nil errors as values. This is useful for converting a value sequence to a key-error sequence where all errors are nil (indicating success).

func SetToRandomizedSlice

func SetToRandomizedSlice[S ~map[T]struct{}, T cmp.Ordered](set S) []T

SetToRandomizedSlice converts a set to a slice with values in random order.

func SetToSortedSlice

func SetToSortedSlice[S ~map[T]struct{}, T cmp.Ordered](set S) []T

SetToSortedSlice converts a set to a slice with values in sorted order.

func SliceContainsAll

func SliceContainsAll[T comparable](outer []T, inner ...T) bool

SliceContainsAll returns true if outer contains all elements of inner. It returns false if outer has fewer elements than inner or if any element in inner is not found in outer.

func SliceContainsAny

func SliceContainsAny[T comparable](outer []T, inner ...T) bool

SliceContainsAny returns true if outer contains any element of inner. It returns true as soon as the first element from inner is found in outer, false if none of the elements in inner are found in outer.

func TryValidate

func TryValidate(v any) (err error, isValidatable bool)

TryValidate returns an error and true if v implements ValidatErr or Validator and the methods ValidatErr.Validate() or Validator.Valid() indicate an invalid value. The error from ValidatErr.Validate() is returned directly, and ErrInvalidValue is returned if Validator.Valid() is false. If v does not implement ValidatErr or Validator then nil and false will be returned. The boolean return value indicates whether the value was validatable.

func Validate

func Validate(v any) error

Validate returns an error if v implements ValidatErr or Validator and the methods ValidatErr.Validate() or Validator.Valid() indicate an invalid value. The error from ValidatErr.Validate() is returned directly, and ErrInvalidValue is returned if Validator.Valid() is false. If v does not implement ValidatErr or Validator then nil will be returned.

func Yield

func Yield[V any](value V) iter.Seq[V]

Yield returns an iterator that yields a single value. This is useful for converting a single value into an iterator sequence.

func Yield2

func Yield2[K, V any](key K, value V) iter.Seq2[K, V]

Yield2 returns an iterator that yields a single key-value pair. This is useful for converting a single key-value pair into an iterator sequence.

func YieldErr

func YieldErr[K any](err error) iter.Seq2[K, error]

YieldErr returns an iterator that yields a single key-value pair with the default value for the key type K and the passed error as the value. This is useful for propagating errors through iterator sequences.

Types

type Finder

type Finder interface {
	// FindAllIndex finds all occurrences of the pattern in str and returns
	// a slice of index pairs [start, end] for each match.
	// The parameter n limits the number of matches returned:
	//   - n < 0: return all matches
	//   - n == 0: return no matches
	//   - n > 0: return at most n matches
	FindAllIndex(str []byte, n int) [][]int
}

Finder defines an interface for finding patterns in byte slices. It provides a method to find all occurrences of a pattern within a string, returning the start and end indices of each match.

type KeyMutex

type KeyMutex[T comparable] struct {
	// contains filtered or unexported fields
}

KeyMutex manages a unique mutex for every locked key. The mutex for a key exists as long as there are any locks waiting to be unlocked. This is equivalent to declaring a mutex variable for every key, except that the key and the number of mutexes are dynamic.

func NewKeyMutex

func NewKeyMutex[T comparable]() *KeyMutex[T]

NewKeyMutex returns a new KeyMutex

func (*KeyMutex[T]) IsLocked

func (m *KeyMutex[T]) IsLocked(key T) bool

IsLocked tells wether a key is locked.

func (*KeyMutex[T]) Lock

func (m *KeyMutex[T]) Lock(key T)

Lock the mutex for a given key

func (*KeyMutex[T]) Unlock

func (m *KeyMutex[T]) Unlock(key T)

Unlock the mutex for a given key.

type LenString

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

LenString holds a string together with a minimum and maximum length constraints. It implements validation to ensure the string length falls within the specified bounds. LenString implements the encoding.UnmarshalText, json.Unmarshaler, and strfmt.StringAssignable interfaces that will perform length validation.

func MustLenString

func MustLenString(str string, min, max int) LenString

MustLenString returns a LenString or panics on errors from Validate. Use this when you're certain the string meets the length constraints.

func NewLenString

func NewLenString(str string, min, max int) *LenString

NewLenString returns a new LenString without validating it. Use this when you want to create a LenString and validate it separately.

func (*LenString) MarshalJSON

func (s *LenString) MarshalJSON() (text []byte, err error)

MarshalJSON implements the json.Marshaler interface.

func (*LenString) MarshalText

func (s *LenString) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

func (*LenString) MaxLen

func (s *LenString) MaxLen() int

MaxLen returns the maximum allowed length for the string.

func (*LenString) MinLen

func (s *LenString) MinLen() int

MinLen returns the minimum allowed length for the string.

func (*LenString) ScanString

func (s *LenString) ScanString(source string, validate bool) error

ScanString tries to parse and assign the passed source string as value of the implementing type.

If validate is true, the source string is checked for validity before it is assigned to the type.

If validate is false and the source string can still be assigned in some non-normalized way it will be assigned without returning an error.

func (*LenString) SetString

func (s *LenString) SetString(str string) error

SetString sets the string value after validating it against the length constraints. Returns an error if the string doesn't meet the length requirements.

func (*LenString) String

func (s *LenString) String() string

String returns the string or "<nil>". String implements the fmt.Stringer interface.

func (*LenString) UnmarshalJSON

func (s *LenString) UnmarshalJSON(text []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. It validates the string length after unmarshaling from JSON.

func (*LenString) UnmarshalText

func (s *LenString) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. It validates the text length before setting the string value.

func (*LenString) Validate

func (s *LenString) Validate() error

Validate implements the ValidatErr interface. It checks that the minimum and maximum lengths are valid and that the string length falls within the specified bounds.

type Normalizable

type Normalizable[T any] interface {
	// Normalized returns the normalized value of type T or an error if normalization fails.
	Normalized() (T, error)
}

Normalizable is a generic interface for types that can be normalized to a standard form. Normalization typically involves converting input data to a consistent, validated format. This interface is commonly implemented by types that handle user input or external data that may come in various formats but need to be standardized.

The Normalized method should: - Return the normalized value in its standard form - Return an error if the value cannot be normalized - Be idempotent (calling Normalized on an already normalized value should return the same result)

type NormalizableValidator

type NormalizableValidator[T any] interface {
	Validator
	Normalizable[T]

	// ValidAndNormalized returns true if the value is both valid and already in normalized form.
	// This is a performance optimization that avoids the need to call both Valid() and Normalized()
	// separately when checking if a value is ready for use.
	ValidAndNormalized() bool
}

NormalizableValidator is a generic interface that combines validation and normalization capabilities. It extends both the Validator interface and Normalizable interface, providing a comprehensive solution for types that need both validation and normalization functionality.

This interface is particularly useful for types that: - Accept input in various formats - Need to validate the input before normalization - Should provide a quick check for both validity and normalization status

type Set

type Set[T cmp.Ordered] map[T]struct{}

Set represents a collection of unique ordered values. It is implemented as a map[T]struct{} for efficient lookups and memory usage. The type parameter T must be comparable and ordered (implements cmp.Ordered).

func NewSet

func NewSet[T cmp.Ordered](vals ...T) Set[T]

NewSet creates a new Set containing the provided values. Duplicate values are automatically deduplicated.

func (Set[T]) Add

func (set Set[T]) Add(val T)

Add adds a value to the set.

func (Set[T]) AddSet

func (set Set[T]) AddSet(other Set[T])

AddSet adds all values from another set to this set.

func (Set[T]) AddSlice

func (set Set[T]) AddSlice(vals []T)

AddSlice adds all values from the slice to the set.

func (Set[T]) Clear

func (set Set[T]) Clear()

Clear removes all values from the set.

func (Set[T]) Clone

func (set Set[T]) Clone() Set[T]

Clone creates a deep copy of the set.

func (Set[T]) Contains

func (set Set[T]) Contains(val T) bool

Contains returns true if the set contains the specified value.

func (Set[T]) ContainsAll

func (set Set[T]) ContainsAll(vals ...T) bool

ContainsAll returns true if the set contains all of the specified values.

func (Set[T]) ContainsAny

func (set Set[T]) ContainsAny(vals ...T) bool

ContainsAny returns true if the set contains any of the specified values.

func (Set[T]) ContainsSet

func (set Set[T]) ContainsSet(other Set[T]) bool

ContainsSet returns true if this set contains all values from the other set.

func (Set[T]) Delete

func (set Set[T]) Delete(val T)

Delete removes a value from the set.

func (Set[T]) DeleteSet

func (set Set[T]) DeleteSet(other Set[T])

DeleteSet removes all values from the other set from this set.

func (Set[T]) DeleteSlice

func (set Set[T]) DeleteSlice(vals []T)

DeleteSlice removes all values from the slice from the set.

func (Set[T]) Difference

func (set Set[T]) Difference(other Set[T]) Set[T]

Difference returns a new set containing values that exist in either set but not in both.

func (Set[T]) Equal

func (set Set[T]) Equal(other Set[T]) bool

Equal returns true if both sets contain exactly the same values.

func (Set[T]) GetOne

func (set Set[T]) GetOne() T

GetOne returns one element of the set or the default value for T if the set is empty. The element returned is not guaranteed to be any specific element from the set.

func (Set[T]) Intersection

func (set Set[T]) Intersection(other Set[T]) Set[T]

Intersection returns a new set containing only values that exist in both sets.

func (Set[T]) IsEmpty

func (set Set[T]) IsEmpty() bool

IsEmpty returns true if the set is empty or nil.

func (Set[T]) IsNull

func (set Set[T]) IsNull() bool

IsNull implements the nullable.Nullable interface by returning true if the set is nil.

func (Set[T]) Len

func (set Set[T]) Len() int

Len returns the number of values in the set. Returns zero for a nil set.

func (Set[T]) Map

func (set Set[T]) Map(mapFunc func(T) (T, bool)) Set[T]

Map applies a transformation function to each value in the set and returns a new set containing the results. The mapFunc should return the transformed value and a boolean indicating whether to include the result in the new set.

func (Set[T]) MarshalJSON

func (set Set[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by returning the JSON null value for an empty (null) string.

func (Set[T]) Sorted

func (set Set[T]) Sorted() []T

Sorted returns a slice containing all values in the set, sorted in ascending order.

func (Set[T]) String

func (set Set[T]) String() string

String implements the fmt.Stringer interface. Returns a string representation of the set with values in sorted order.

func (Set[T]) Union

func (set Set[T]) Union(other Set[T]) Set[T]

Union returns a new set containing all values from both this set and the other set.

func (*Set[T]) UnmarshalJSON

func (set *Set[T]) UnmarshalJSON(j []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. It unmarshals a JSON array into the set, removing any duplicates.

type StaticValidatErr

type StaticValidatErr struct {
	Err error
}

StaticValidatErr implements the ValidatErr interface for a validation error value. This is useful when you have a pre-computed validation error.

func (StaticValidatErr) Validate

func (v StaticValidatErr) Validate() error

Validate returns an error if the data of the implementation is not valid.

type StaticValidator

type StaticValidator bool

StaticValidator implements the Validator interface with a bool validity value. This is useful when you have a pre-computed validation result.

func (StaticValidator) Valid

func (valid StaticValidator) Valid() bool

Valid returns if the data of the implementation is valid.

type ValidatErr

type ValidatErr interface {
	// Validate returns an error if the data of the implementation is not valid.
	Validate() error
}

ValidatErr can be implemented by types that can validate their data and return detailed error information. This is more informative than the Validator interface as it provides specific error details.

func CombinedValidatErr

func CombinedValidatErr(validatErrs ...ValidatErr) ValidatErr

CombinedValidatErr creates a ValidatErr whose Validate method returns the first error from the passed validatErrs Validate methods or nil if none returned an error. This is equivalent to creating a ValidatErrs slice.

type ValidatErrFunc

type ValidatErrFunc func() error

ValidatErrFunc implements the ValidatErr interface with a function. This allows you to use a function as a validator that returns detailed errors.

func (ValidatErrFunc) Validate

func (f ValidatErrFunc) Validate() error

Validate returns an error if the data of the implementation is not valid.

type ValidatErrs

type ValidatErrs []ValidatErr

ValidatErrs is a slice of ValidatErr implementations. It implements the ValidatErr interface itself, returning the first error encountered.

func (ValidatErrs) Validate

func (v ValidatErrs) Validate() error

Validate returns an error if the data of the implementation is not valid. Returns the first error from any validator in the slice, or nil if all are valid.

type Validator

type Validator interface {
	// Valid returns if the data of the implementation is valid.
	Valid() bool
}

Validator can be implemented by types that can validate their data. The Valid method should return true if the data is valid, false otherwise.

func CombinedValidator

func CombinedValidator(validators ...Validator) Validator

CombinedValidator creates a Validator whose Valid method returns false if any of the passed validators Valid methods returned false, else it returns true. This is equivalent to creating a Validators slice.

type ValidatorAsValidatErr

type ValidatorAsValidatErr struct {
	Validator
}

ValidatorAsValidatErr wraps a Validator as a ValidatErr, returning ErrInvalidValue when Validator.Valid() returns false. This allows you to use a simple boolean validator in contexts that require detailed error information.

func (ValidatorAsValidatErr) Validate

func (v ValidatorAsValidatErr) Validate() error

Validate returns an error if the wrapped validator is not valid.

type ValidatorFunc

type ValidatorFunc func() bool

ValidatorFunc implements the Validator interface with a function. This allows you to use a function as a validator.

func (ValidatorFunc) Valid

func (f ValidatorFunc) Valid() bool

Valid returns if the data of the implementation is valid.

type Validators

type Validators []Validator

Validators is a slice of Validator implementations. It implements the Validator interface itself, returning true only if all validators are valid.

func (Validators) Valid

func (v Validators) Valid() bool

Valid returns if the data of the implementation is valid. Returns false if any validator in the slice returns false.

Directories

Path Synopsis
Package account provides account number handling with validation, parsing, and database integration for Go applications.
Package account provides account number handling with validation, parsing, and database integration for Go applications.
Package bank provides comprehensive banking data types and utilities for Go applications.
Package bank provides comprehensive banking data types and utilities for Go applications.
findencoding
Package findencoding provides utilities for detecting and testing character encodings in text files, particularly useful for debugging encoding issues and finding the correct encoding for unknown text data.
Package findencoding provides utilities for detecting and testing character encodings in text files, particularly useful for debugging encoding issues and finding the correct encoding for unknown text data.
Package country provides comprehensive country code handling and validation based on ISO 3166-1 alpha-2 standards for Go applications.
Package country provides comprehensive country code handling and validation based on ISO 3166-1 alpha-2 standards for Go applications.
Package date provides comprehensive date handling and validation utilities for Go applications with support for multiple date formats and internationalization.
Package date provides comprehensive date handling and validation utilities for Go applications with support for multiple date formats and internationalization.
Package deref provides safe pointer dereferencing utilities for Go applications.
Package deref provides safe pointer dereferencing utilities for Go applications.
Package email provides comprehensive email address handling, parsing, validation, and message processing utilities for Go applications.
Package email provides comprehensive email address handling, parsing, validation, and message processing utilities for Go applications.
Package float provides utilities for working with floating-point numbers in Go.
Package float provides utilities for working with floating-point numbers in Go.
pq
pq/oid
Package oid contains OID constants as defined by the Postgres server.
Package oid contains OID constants as defined by the Postgres server.
js module
Package language provides comprehensive language code handling and validation based on ISO 639-1 standards for Go applications.
Package language provides comprehensive language code handling and validation based on ISO 639-1 standards for Go applications.
gen-lang-maps command
Package nullable provides interfaces and utilities for handling nullable values in Go.
Package nullable provides interfaces and utilities for handling nullable values in Go.
stringfrom
Package stringfrom provides utilities for converting various Go types to strings with safe handling of nil pointers and customizable default values.
Package stringfrom provides utilities for converting various Go types to strings with safe handling of nil pointers and customizable default values.

Jump to

Keyboard shortcuts

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