validation

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: May 27, 2025 License: MIT Imports: 9 Imported by: 0

README

Validation

A type-safe, composable validation library for Go that leverages generics to provide compile-time safety and runtime flexibility.

Features

  • Type-safe: Built with Go generics for compile-time type safety
  • Composable: Combine validation rules using logical operators (Or, When, Unless)
  • Struct validation: Deep validation of nested structs with field-level error reporting
  • Collection support: Validate slices and maps with element-level validation
  • Rich error context: Detailed error messages with field paths and parameters
  • Extensible: Easy to create custom validation rules
  • Zero dependencies: Pure Go implementation
  • Fatal error handling: Stop validation chains on critical errors

Installation

go get github.com/jacoelho/validation

Quick Start

package main

import (
    "fmt"
    "github.com/jacoelho/validation"
)

type User struct {
    Name  string
    Email string
    Age   int
}

func main() {
    validator := validation.Struct(
        validation.Field("Name", 
            func(u User) string { return u.Name },
            validation.NotZero[string](),
            validation.StringsRuneMinLength[string](2),
        ),
        validation.Field("Email",
            func(u User) string { return u.Email },
            validation.NotZero[string](),
            validation.StringsMatchesRegex[string](`^[^@]+@[^@]+\.[^@]+$`),
        ),
        validation.Field("Age",
            func(u User) int { return u.Age },
            validation.NumbersMin(18),
            validation.NumbersMax(120),
        ),
    )

    user := User{Name: "A", Email: "invalid", Age: 15}
    
    if errs := validator.Validate(user); errs.HasErrors() {
        for _, err := range errs {
            fmt.Println(err.Error())
        }
        // Output:
        // min (field: Name) {actual: 1, min: 2}
        // regex (field: Email) {pattern: ^[^@]+@[^@]+\.[^@]+$}
        // min (field: Age) {actual: 15, min: 18}
    }
}

Core Concepts

Rules

Rules are functions that validate a single value and return an error if validation fails:

type Rule[T any] func(value T) *Error
Validators

Validators coordinate multiple rules and provide structured validation for complex types like structs, slices, and maps.

Errors

Validation errors include field paths, error codes, and contextual parameters:

type Error struct {
    Field  string                 // Field path (e.g., "User.Address.City")
    Code   string                 // Error code (e.g., "required", "min")
    Params map[string]any         // Additional error parameters
    Fatal  bool                   // Whether to stop validation
}

Validation Rules Reference

Core Rules
// Basic validation
validation.NotZero[string]()                           // Not zero value
validation.NotZeroable[time.Time]()                    // For types with IsZero() method
validation.OneOf[string]("admin", "user", "guest")     // Value must be one of specified values
validation.NotOneOf[string]("root", "admin")           // Value must not be one of specified values

// Logical operators
validation.RuleNot(validation.NotZero[string]())       // Negate a rule
validation.Or(rule1, rule2, rule3)                     // Any rule must pass
validation.When(condition, rule)                       // Apply rule conditionally
validation.Unless(condition, rule)                     // Apply rule unless condition

// Control flow
validation.RuleStopOnError(rule)                       // Stop validation on error
String Validation
validation.NotZero[string]()                                   // Non-empty
validation.StringsRuneMinLength[string](5)                     // Min rune length
validation.StringsRuneMaxLength[string](100)                   // Max rune length
validation.StringsRuneLengthBetween[string](5, 100)           // Length range
validation.StringsMatchesRegex[string](`^\w+@\w+\.\w+$`)      // Regex pattern
validation.StringsContains[string]("@")                       // Contains substring
Numeric Validation
validation.NumbersMin(18)                    // Minimum value
validation.NumbersMax(65)                    // Maximum value
validation.NumbersBetween(18, 65)            // Range validation
validation.NumbersPositive[int]()            // Greater than zero
validation.NumbersNegative[int]()            // Less than zero
validation.NumbersNonNegative[int]()         // Greater than or equal to zero
validation.NumbersNonPositive[int]()         // Less than or equal to zero
Time Validation
now := time.Now()
validation.TimeBefore(now)                   // Before specific time
validation.TimeBeforeOrEqual(now)            // Before or equal to specific time
validation.TimeAfter(now.AddDate(-1, 0, 0))  // After specific time
validation.TimeAfterOrEqual(now)             // After or equal to specific time
validation.TimeBetween(start, end)           // Between time range
Slice Validation
validation.SlicesMinLength[string](1)                    // Minimum length
validation.SlicesMaxLength[string](10)                   // Maximum length
validation.SlicesLength[string](5)                       // Exact length
validation.SlicesInBetweenLength[string](1, 10)         // Length range
validation.SlicesUnique[string]()                       // All elements unique
validation.SlicesContains[string]("required")           // Contains value
validation.SlicesOneOf[string]("a", "b", "c")           // Elements must be one of specified values
validation.SlicesNotOneOf[string]("x", "y")             // Elements must not be one of specified values
validation.SlicesAtIndex(1, validation.NotZero[string]()) // Element at index 

// Validate each element
validation.SlicesForEach(
    validation.NotZero[string](),
    validation.StringsRuneMaxLength[string](50),
)
Map Validation
// Map validation rules
validation.MapsMinKeys[string, string](1)               // Minimum number of keys
validation.MapsMaxKeys[string, string](10)              // Maximum number of keys
validation.MapsLength[string, string](5)                // Exact number of keys
validation.MapsLengthBetween[string, string](1, 10)     // Range of key count
validation.MapsKey[string, string]("key",               // Validate specific key
    validation.NotZero[string](),
)
validation.MapsKeysOneOf[string, string]("a", "b")      // Keys must be one of specified values
validation.MapsKeysNotOneOf[string, string]("x")        // Keys must not be one of specified values
validation.MapsValuesOneOf[string, string]("y", "z")    // Values must be one of specified values
validation.MapsValuesNotOneOf[string, string]("bad")    // Values must not be one of specified values

// Validate each key-value pair
validation.MapsForEach(func(key, value string) *validation.Error {
    if value == "" {
        return &validation.Error{
            Code:   "empty_value",
            Params: map[string]any{"key": key},
        }
    }
    return nil
})

Struct Validation

Basic Example
type Person struct {
    Name string
    Age  int
}

validator := validation.Struct(
    validation.Field("Name", 
        func(p Person) string { return p.Name },
        validation.NotZero[string](),
        validation.StringsRuneMinLength[string](2),
        validation.StringsRuneMaxLength[string](50),
    ),
    validation.Field("Age",
        func(p Person) int { return p.Age },
        validation.NumbersMin(0),
        validation.NumbersMax(150),
    ),
)

person := Person{Name: "John", Age: 30}
errs := validator.Validate(person)
Nested Struct Validation
type Address struct {
    Street string
    City   string
    ZIP    string
}

type User struct {
    Name    string
    Email   string
    Address Address
}

// Create address validator
addressValidator := validation.Struct(
    validation.Field("Street", func(a Address) string { return a.Street },
        validation.NotZero[string](),
        validation.StringsRuneMinLength[string](5),
    ),
    validation.Field("City", func(a Address) string { return a.City },
        validation.NotZero[string](),
        validation.StringsRuneMinLength[string](2),
    ),
    validation.Field("ZIP", func(a Address) string { return a.ZIP },
        validation.NotZero[string](),
        validation.StringsMatchesRegex[string](`^\d{5}(-\d{4})?$`),
    ),
)

// Create user validator with nested address
userValidator := validation.Struct(
    validation.Field("Name", func(u User) string { return u.Name },
        validation.NotZero[string](),
    ),
    validation.Field("Email", func(u User) string { return u.Email },
        validation.NotZero[string](),
        validation.StringsMatchesRegex[string](`^[^@]+@[^@]+\.[^@]+$`),
    ),
    validation.StructField("Address", func(u User) Address { return u.Address },
        addressValidator),
)

user := User{
    Name:  "John Doe",
    Email: "[email protected]",
    Address: Address{
        Street: "123 Main St",
        City:   "Anytown",
        ZIP:    "12345",
    },
}

errs := userValidator.Validate(user)
if errs.HasErrors() {
    for _, err := range errs {
        fmt.Printf("Field: %s, Error: %s\n", err.Field, err.Code)
        // Example output: "Field: Address.ZIP, Error: regex"
    }
}
Collection Fields
type User struct {
    Name     string
    Tags     []string
    Settings map[string]string
}

validator := validation.Struct(
    validation.Field("Name", func(u User) string { return u.Name },
        validation.NotZero[string](),
    ),
    
    // Slice validation
    validation.SliceField("Tags", func(u User) []string { return u.Tags },
        validation.SlicesMinLength[string](1),
        validation.SlicesMaxLength[string](5),
        validation.SlicesUnique[string](),
        validation.SlicesForEach(
            validation.NotZero[string](),
            validation.StringsRuneMaxLength[string](20),
        ),
    ),
    
    // Map validation
    validation.MapField("Settings", func(u User) map[string]string { return u.Settings },
        validation.MapsMaxKeys[string, string](10),
        validation.MapsForEach(func(k, v string) *validation.Error {
            if v == "" {
                return &validation.Error{
                    Code:   "empty_setting_value",
                    Params: map[string]any{"key": k},
                }
            }
            return nil
        }),
    ),
)

Error Handling

Checking for Errors
errs := validator.Validate(data)

// Check if any errors exist
if errs.HasErrors() {
    // Handle validation errors
}

// Check for fatal errors (validation stopped early)
if errs.HasFatalErrors() {
    // Handle critical validation failures
}
Error Formatting
// Default error formatting
fmt.Println(errs.Error())
// Output: "required (field: Name); min (field: Age) {actual: 15, min: 18}"

// Custom formatting
customFormat := errs.Format(func(e *validation.Error) string {
    return fmt.Sprintf("%s: %s", e.Field, e.Code)
}, "\n")
fmt.Println(customFormat)
// Output:
// Name: required
// Age: min

// Individual error details
for _, err := range errs {
    fmt.Printf("Field: %s\n", err.Field)
    fmt.Printf("Code: %s\n", err.Code)
    fmt.Printf("Params: %v\n", err.Params)
    fmt.Printf("Fatal: %t\n", err.Fatal)
}

Custom Validation Rules

Simple Custom Rule
func ValidateEmail() validation.Rule[string] {
    return func(value string) *validation.Error {
        if !strings.Contains(value, "@") || !strings.Contains(value, ".") {
            return &validation.Error{
                Code: "invalid_email",
                Params: map[string]any{
                    "value": value,
                },
            }
        }
        return nil
    }
}

// Usage
validation.Field("Email", func(u User) string { return u.Email },
    ValidateEmail(),
)
Parameterized Custom Rule
func StringContainsAny(substrings ...string) validation.Rule[string] {
    return func(value string) *validation.Error {
        for _, substr := range substrings {
            if strings.Contains(value, substr) {
                return nil
            }
        }
        return &validation.Error{
            Code: "missing_required_substring",
            Params: map[string]any{
                "value":      value,
                "substrings": substrings,
            },
        }
    }
}

// Usage
validation.Field("Description", func(p Product) string { return p.Description },
    StringContainsAny("premium", "deluxe", "pro"),
)

Advanced Usage

Conditional Validation
type User struct {
    Type       string
    CreditCard string
    BankAccount string
}

validator := validation.Struct(
    validation.Field("Type", func(u User) string { return u.Type },
        validation.OneOf[string]("basic", "premium"),
    ),
    
    // Require credit card for premium users
    validation.Field("CreditCard", func(u User) string { return u.CreditCard },
        validation.When(
            func(u User) bool { return u.Type == "premium" },
            validation.NotZero[string](),
        ),
    ),
    
    // Bank account is optional for basic users, forbidden for premium
    validation.Field("BankAccount", func(u User) string { return u.BankAccount },
        validation.Unless(
            func(u User) bool { return u.Type == "premium" },
            validation.NotZero[string](),
        ),
    ),
)
Complex Logical Validation
// Either email or phone must be provided
validation.Field("ContactInfo", func(u User) User { return u },
    validation.Or(
        validation.Field("Email", func(u User) string { return u.Email },
            validation.NotZero[string](),
        ),
        validation.Field("Phone", func(u User) string { return u.Phone },
            validation.NotZero[string](),
        ),
    ),
)
Fatal Error Handling
validation.Field("Password", func(u User) string { return u.Password },
    // Stop validation if password is missing
    validation.RuleStopOnError(validation.NotZero[string]()),
    
    // These rules only run if password is present
    validation.StringsRuneMinLength[string](8),
    validation.StringsMatchesRegex[string](`[A-Z]`), // Must contain uppercase
    validation.StringsMatchesRegex[string](`[0-9]`), // Must contain number
)
Validation Groups
// Create reusable validation groups
var (
    emailRules = []validation.Rule[string]{
        validation.NotZero[string](),
        validation.StringsMatchesRegex[string](`^[^@]+@[^@]+\.[^@]+$`),
        validation.StringsRuneMaxLength[string](100),
    }
    
    passwordRules = []validation.Rule[string]{
        validation.NotZero[string](),
        validation.StringsRuneMinLength[string](8),
        validation.StringsMatchesRegex[string](`[A-Z]`),
        validation.StringsMatchesRegex[string](`[a-z]`),
        validation.StringsMatchesRegex[string](`[0-9]`),
    }
)

userValidator := validation.Struct(
    validation.Field("Email", func(u User) string { return u.Email }, emailRules...),
    validation.Field("Password", func(u User) string { return u.Password }, passwordRules...),
)

License

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

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/jacoelho/validation"
)

func main() {
	// Define a user struct with slices and maps
	type User struct {
		Name     string
		Age      int
		Email    string
		Password string
		Tags     []string
		Settings map[string]string
	}

	// Create a validator for the User struct
	validator := validation.Struct(
		validation.Field("Name", func(u User) string { return u.Name },
			validation.NotZero[string](),
			validation.StringsRuneMaxLength[string](50),
		),
		validation.Field("Age", func(u User) int { return u.Age },
			validation.NumbersMin(18),
			validation.NumbersMax(120),
		),
		validation.Field("Email", func(u User) string { return u.Email },
			validation.NotZero[string](),
			validation.StringsRuneMaxLength[string](100),
		),
		validation.Field("Password", func(u User) string { return u.Password },
			validation.NotZero[string](),
			validation.StringsRuneMinLength[string](8),
		),
		validation.SliceField("Tags", func(u User) []string { return u.Tags },
			validation.SlicesMaxLength[string](5),
			validation.SlicesForEach(
				validation.NotZero[string](),
				validation.StringsRuneMaxLength[string](20),
			),
		),
		validation.MapField("Settings", func(u User) map[string]string { return u.Settings },
			validation.MapsMaxKeys[string, string](5),
			validation.MapsForEach(
				func(k, v string) *validation.Error {
					if v == "" {
						return &validation.Error{
							Code:   "empty_value",
							Field:  k,
							Params: map[string]any{"key": k},
						}
					}
					return nil
				},
			),
			validation.MapsKey("lang", validation.OneOf("en", "fr")),
		),
	)

	// Validate a valid user
	validUser := User{
		Name:     "John Doe",
		Age:      30,
		Email:    "[email protected]",
		Password: "secure123",
		Tags:     []string{"user", "premium"},
		Settings: map[string]string{
			"theme": "dark",
			"lang":  "en",
		},
	}
	err := validator.Validate(validUser)
	fmt.Println("Valid user errors:", len(err))

	// Validate an invalid user
	invalidUser := User{
		Name:     "",
		Age:      15,
		Email:    "invalid-email",
		Password: "short",
		Tags:     []string{"", "very_long_tag_that_exceeds_maximum_length"},
		Settings: map[string]string{
			"theme": "",
			"lang":  "en",
		},
	}
	err = validator.Validate(invalidUser)
	fmt.Println("Invalid user errors:", err)

}
Output:

Valid user errors: 0
Invalid user errors: zero (field: Name); min (field: Age) {actual: 15, min: 18}; min (field: Password) {actual: 5, min: 8}; zero (field: Tags.0); max (field: Tags.1) {actual: 41, max: 20}; empty_value (field: Settings.theme) {key: theme}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	Field  string
	Code   string
	Params map[string]any
	Fatal  bool
}

Error represents a single validation error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type Errors

type Errors []*Error

Errors is a collection of validation errors.

func SingleErrorSlice added in v1.0.5

func SingleErrorSlice(field, code string, params map[string]any, fatal bool) Errors

SingleErrorSlice creates a new Errors instance with a single error.

func (Errors) Error

func (errs Errors) Error() string

Error returns a concatenated string of all errors.

func (Errors) Format

func (errs Errors) Format(f func(e *Error) string, sep string) string

Format formats the errors using the given function and separator.

func (Errors) HasErrors

func (errs Errors) HasErrors() bool

HasErrors reports whether any errors exist.

func (Errors) HasFatalErrors

func (errs Errors) HasFatalErrors() bool

HasFatalErrors reports whether any fatal errors exist.

type FieldAccessor

type FieldAccessor[T, F any] struct {
	// contains filtered or unexported fields
}

FieldAccessor is a field of a struct.

func Field

func Field[T, F any](name string, getter func(T) F, rules ...Rule[F]) FieldAccessor[T, F]

Field creates a new FieldAccessor with the given name, getter and rules.

func MapField

func MapField[T any, K comparable, V any](name string, getter func(T) map[K]V, rules ...MapRule[K, V]) FieldAccessor[T, map[K]V]

MapField creates a new FieldAccessor with the given name, getter and rules.

func SliceField

func SliceField[T, E any](name string, getter func(T) []E, rules ...SliceRule[E]) FieldAccessor[T, []E]

SliceField creates a new FieldAccessor with the given name, getter and rules.

func StructField

func StructField[T, F any](name string, getter func(T) F, validator *StructValidator[F]) FieldAccessor[T, F]

StructField creates a new FieldAccessor with the given name, getter and validator.

func (FieldAccessor[T, F]) ValidateWithPrefix

func (fa FieldAccessor[T, F]) ValidateWithPrefix(parent T, prefix string) Errors

ValidateWithPrefix validates the given value with a prefix.

type MapEntryRule

type MapEntryRule[K comparable, V any] func(key K, value V) *Error

MapEntryRule is a function that validates an entry in a map.

type MapRule

type MapRule[K comparable, V any] func(values map[K]V) Errors

MapRule is a function that validates a map of values.

func MapsForEach

func MapsForEach[K comparable, V any](rules ...MapEntryRule[K, V]) MapRule[K, V]

MapsForEach validates each entry in the map using the given rules.

func MapsKey added in v1.0.2

func MapsKey[K comparable, V any](key K, rules ...Rule[V]) MapRule[K, V]

MapsKey validates the value of the given key.

func MapsKeysNotOneOf added in v1.0.5

func MapsKeysNotOneOf[K comparable, V any](disallowed ...K) MapRule[K, V]

MapsKeysNotOneOf validates that the map does not have the given keys.

func MapsKeysOneOf added in v1.0.5

func MapsKeysOneOf[K comparable, V any](allowed ...K) MapRule[K, V]

MapsKeysOneOf validates that the map has only the given keys.

func MapsLength

func MapsLength[K comparable, V any](length int) MapRule[K, V]

func MapsLengthBetween

func MapsLengthBetween[K comparable, V any](min, max int) MapRule[K, V]

func MapsMaxKeys

func MapsMaxKeys[K comparable, V any](max int) MapRule[K, V]

MapsMaxKeys validates that the map has at most the given number of keys.

func MapsMinKeys

func MapsMinKeys[K comparable, V any](min int) MapRule[K, V]

MapsMinKeys validates that the map has at least the given number of keys.

func MapsValuesNotOneOf added in v1.0.5

func MapsValuesNotOneOf[K comparable, V comparable](disallowed ...V) MapRule[K, V]

MapsValuesNotOneOf validates that the map does not have the given values.

func MapsValuesOneOf added in v1.0.5

func MapsValuesOneOf[K comparable, V comparable](allowed ...V) MapRule[K, V]

MapsValuesOneOf validates that the map has only the given values.

type MapValidator

type MapValidator[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapValidator is a validator for maps of values.

func Maps added in v1.0.1

func Maps[K comparable, V any](rules ...MapRule[K, V]) *MapValidator[K, V]

Maps creates a new MapValidator with the given rules.

func (*MapValidator[K, V]) Validate

func (v *MapValidator[K, V]) Validate(values map[K]V) Errors

Validate validates the given values.

func (*MapValidator[K, V]) ValidateWithPrefix

func (v *MapValidator[K, V]) ValidateWithPrefix(values map[K]V, prefix string) Errors

ValidateWithPrefix validates the given values with a prefix.

type Rule

type Rule[T any] func(value T) *Error

Rule is a function that validates a value.

func NotOneOf added in v1.0.5

func NotOneOf[T comparable](disallowed ...T) Rule[T]

NotOneOf validates that the value is not one of the given disallowed values.

func NotZero added in v1.0.5

func NotZero[T comparable]() Rule[T]

NotZero ensures the value is not the zero value for its type

func NotZeroable added in v1.0.5

func NotZeroable[T interface{ IsZero() bool }]() Rule[T]

NotZeroable ensures the value is not the zero value. The zero value is determined by the IsZero method.

func NumbersBetween

func NumbersBetween[T cmp.Ordered](min, max T) Rule[T]

NumbersBetween validates that the value is between the given minimum and maximum (inclusive).

func NumbersMax

func NumbersMax[T cmp.Ordered](max T) Rule[T]

NumbersMax validates that the value is less than or equal to the given maximum.

func NumbersMin

func NumbersMin[T cmp.Ordered](min T) Rule[T]

NumbersMin validates that the value is greater than or equal to the given minimum.

func NumbersNegative

func NumbersNegative[T cmp.Ordered]() Rule[T]

NumbersNegative validates that the value is less than 0.

func NumbersNonNegative added in v1.0.5

func NumbersNonNegative[T cmp.Ordered]() Rule[T]

NumbersNonNegative validates that the value is greater than or equal to 0.

func NumbersNonPositive added in v1.0.5

func NumbersNonPositive[T cmp.Ordered]() Rule[T]

NumbersNonPositive validates that the value is less than or equal to 0.

func NumbersPositive

func NumbersPositive[T cmp.Ordered]() Rule[T]

NumbersPositive validates that the value is greater than 0.

func OneOf added in v1.0.5

func OneOf[T comparable](allowed ...T) Rule[T]

OneOf validates that the value is one of the given allowed values.

func Or

func Or[T any](rules ...Rule[T]) Rule[T]

Or combines multiple rules, at least one must pass. If all rules fail, the last error is returned.

func RuleNot

func RuleNot[T any](rule Rule[T]) Rule[T]

RuleNot negates the rule.

func RuleStopOnError

func RuleStopOnError[T any](rule Rule[T]) Rule[T]

RuleStopOnError stops the validation process if an error occurs.

func StringsContains

func StringsContains[T ~string](substring T) Rule[T]

StringsContains validates that the string contains the given substring.

func StringsMatchesRegex

func StringsMatchesRegex[T ~string](pattern string) Rule[T]

StringsMatchesRegex validates string against a regex pattern

func StringsRuneLengthBetween

func StringsRuneLengthBetween[T ~string](min, max int) Rule[T]

StringsRuneLengthBetween validates string length (in runes, not bytes) between the given minimum and maximum.

func StringsRuneMaxLength

func StringsRuneMaxLength[T ~string](max int) Rule[T]

StringsRuneMaxLength validates maximum string length in runes.

func StringsRuneMinLength

func StringsRuneMinLength[T ~string](min int) Rule[T]

StringsRuneMinLength validates minimum string length in runes.

func TimeAfter

func TimeAfter(other time.Time) Rule[time.Time]

TimeAfter validates that the time is after the given time.

func TimeAfterOrEqual added in v1.0.5

func TimeAfterOrEqual(other time.Time) Rule[time.Time]

TimeAfterOrEqual validates that the time is after the given time.

func TimeBefore

func TimeBefore(other time.Time) Rule[time.Time]

TimeBefore validates that the time is before the given time.

func TimeBeforeOrEqual added in v1.0.5

func TimeBeforeOrEqual(other time.Time) Rule[time.Time]

TimeBeforeOrEqual validates that the time is before the given time.

func TimeBetween

func TimeBetween(min, max time.Time) Rule[time.Time]

TimeBetween validates that the time is between the given times.

func Unless

func Unless[T any](condition func(T) bool, rule Rule[T]) Rule[T]

Unless applies a rule only if the condition is false

func When

func When[T any](condition func(T) bool, rule Rule[T]) Rule[T]

When applies a rule only if the condition is true.

type SliceRule

type SliceRule[T any] func(values []T) Errors

SliceRule is a function that validates a slice of values.

func SlicesAtIndex added in v1.0.4

func SlicesAtIndex[T any](index int, rules ...Rule[T]) SliceRule[T]

SlicesAtIndex validates the value at the given index.

func SlicesContains

func SlicesContains[T comparable](value T) SliceRule[T]

SlicesContains validates that the slice contains the given value.

func SlicesForEach

func SlicesForEach[T any](rules ...Rule[T]) SliceRule[T]

SlicesForEach validates each value in the slice using the given rules.

func SlicesInBetweenLength

func SlicesInBetweenLength[T any](min, max int) SliceRule[T]

SlicesInBetweenLength validates that the slice has between the given lengths.

func SlicesLength

func SlicesLength[T any](length int) SliceRule[T]

SlicesLength validates that the slice has the given length.

func SlicesMaxLength

func SlicesMaxLength[T any](max int) SliceRule[T]

SlicesMaxLength validates that the slice has at most the given length.

func SlicesMinLength

func SlicesMinLength[T any](min int) SliceRule[T]

SlicesMinLength validates that the slice has at least the given length.

func SlicesNotOneOf added in v1.0.5

func SlicesNotOneOf[T comparable](disallowed ...T) SliceRule[T]

SlicesNotOneOf validates that the slice does not contain the given values.

func SlicesOneOf added in v1.0.5

func SlicesOneOf[T comparable](allowed ...T) SliceRule[T]

SlicesOneOf validates that the slice contains only the given values.

func SlicesUnique

func SlicesUnique[T comparable]() SliceRule[T]

SlicesUnique validates that the slice has unique values.

type SliceValidator

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

SliceValidator is a validator for slices of values.

func Slices added in v1.0.1

func Slices[T any](rules ...SliceRule[T]) *SliceValidator[T]

Slices creates a new SliceValidator with the given rules.

func (*SliceValidator[T]) Validate

func (v *SliceValidator[T]) Validate(values []T) Errors

Validate validates the given values.

func (*SliceValidator[T]) ValidateWithPrefix

func (v *SliceValidator[T]) ValidateWithPrefix(values []T, prefix string) Errors

ValidateWithPrefix validates the given values with a prefix.

type StructValidator

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

StructValidator is a validator for a struct.

func Struct added in v1.0.1

func Struct[T any](fields ...fieldValidator[T]) *StructValidator[T]

Struct creates a new StructValidator with the given fields.

func (*StructValidator[T]) Validate

func (v *StructValidator[T]) Validate(value T) Errors

Validate validates the given value.

func (*StructValidator[T]) ValidateWithPrefix

func (v *StructValidator[T]) ValidateWithPrefix(value T, prefix string) Errors

ValidateWithPrefix validates the given value with a prefix.

Jump to

Keyboard shortcuts

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