valex

package module
v0.0.0-...-79dd68e Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 20 Imported by: 0

README

Valex

Valex is an extensible validation library for Go. It provides a flexible way to define type-safe validators and wrap values in a way that ensures they satisfy custom validation rules before being set.

Features

  • Generic Validators: Define validators for any ordered type (e.g. integers, floats, strings).
  • Validator Interface & Adapter: Implement your own validation logic via the Validator[T] interface or create quick validators using the ValidatorFunc[T] adapter.
  • Validated Value Wrapper: Use the ValidatedValue[T] type to ensure that only valid values (as determined by your validator) are set.
  • Tag-Based Validation: Use struct tags with built-in directives via ValidateStruct.
  • Custom Directives: Register your own tag directives with RegisterDirective.

Installation

To add Valex to your project, run:

go get -u github.com/tedla-brandsema/valex@latest

Examples

Defining a Custom Validator

Implement the Validator[T] interface for your type. For example, here’s a simple integer range validator:

package main

import (
	"fmt"
	"github.com/tedla-brandsema/valex"
)

type IntRangeValidator struct {
	Min int
	Max int
}

func (v IntRangeValidator) Validate(val int) (bool, error) {
	if val < v.Min || val > v.Max {
		return false, fmt.Errorf("value %d is out of range [%d, %d]", val, v.Min, v.Max)
	}
	return true, nil
}

func main() {
	// Create a Validator
	v := IntRangeValidator{
		Min: 1,
		Max: 10,
	}

	if ok, err := v.Validate(11); !ok {
		fmt.Println("Error:", err)
	}

	// Or use a Validator in conjunction with a ValidatedValue
	vv := valex.ValidatedValue[int]{
		Validator: v,
	}
	
	if err := vv.Set(5); err != nil {
		fmt.Println("Error:", err)
		return
	}
	
	fmt.Println("Validated value:", vv.Get())
}
Using ValidatorFunc

You can also use the ValidatorFunc[T] adapter to quickly create validators from functions:

package main

import (
	"fmt"
	"github.com/tedla-brandsema/valex"
)

func main() {
	// Create a validator for strings that ensures they are non-empty.
	nonEmptyValidator := valex.ValidatorFunc[string](func(val string) (bool, error) {
		if val == "" {
			return false, fmt.Errorf("string cannot be empty")
		}
		return true, nil
	})

	vv := valex.ValidatedValue[string]{
		Validator: nonEmptyValidator,
	}

	if err := vv.Set("hello world"); err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Validated value:", vv.Get())
}
Tag-Based Validation

You can validate struct fields by using the val tag and calling ValidateStruct. Optionally pass additional tagex.Tag values to process multiple tags in one pass:

package main

import (
	"fmt"
	"github.com/tedla-brandsema/valex"
	"github.com/tedla-brandsema/tagex"
)

type User struct {
	Name  string `val:"min,size=3"`
	Email string `val:"email"`
	Age   int    `val:"rangeint,min=0,max=120"`
}

func main() {
	user := &User{Name: "Al", Email: "invalid", Age: 200}
	tag := tagex.NewTag("extra")
	ok, err := valex.ValidateStruct(user, &tag)
	fmt.Println(ok, err)
}
Registering Custom Directives

Register your own directives to extend the val tag:

package main

import (
	"fmt"
	"github.com/tedla-brandsema/valex"
	"github.com/tedla-brandsema/tagex"
)

type EvenDirective struct{}

func (d *EvenDirective) Name() string { return "even" }
func (d *EvenDirective) Mode() tagex.DirectiveMode {
	return tagex.EvalMode
}
func (d *EvenDirective) Handle(val int) (int, error) {
	if val%2 != 0 {
		return 0, fmt.Errorf("value %d is not even", val)
	}
	return val, nil
}

func main() {
	valex.RegisterDirective(&EvenDirective{})

	type Item struct {
		Count int `val:"even"`
	}

	item := &Item{Count: 3}
	ok, err := valex.ValidateStruct(item)
	fmt.Println(ok, err)
}
Form Validation

NewFormValidator calls request.ParseForm(), which parses both POST bodies and URL query parameters. That means you can use FormValidator with GET requests as well as standard form submissions.

For convenience, ValidateForm wraps request parsing and validation and returns a FormError with an HTTP status code you can use for responses. If you only need binding (outside of HTTP handlers), BindFormValues accepts url.Values directly.

How It Works
  • Validator Interface:
    Define a type that implements the method:Validate(val T) (ok bool, err error) A successful validation should return true (with a nil error), whereas a failure should return false and an appropriate error message.

  • ValidatedValue:
    This type holds a value of type T along with an associated Validator[T].

    • Set(val T) error: Uses the validator to ensure that only valid values are stored.
    • Get() T: Returns the current value.

Built-in Validators

Validator Type Tag Params (defaults) Description
Generic
CmpRangeValidator[T] cmp.Ordered - min, max Inclusive range for ordered types.
NonZeroValidator[T] any - - Value is not zero.
Ints
IntRangeValidator int rangeint min, max Inclusive int range.
MinIntValidator int minint min Int greater than or equal to min.
MaxIntValidator int maxint max Int less than or equal to max.
NonNegativeIntValidator int posint - Int is non-negative.
NonPositiveIntValidator int negint - Int is non-positive.
NonZeroIntValidator int !zeroint (alias: nonzeroint) - Int is not zero.
OneOfIntValidator int oneofint values Int is in values (pipe-separated list).
Float64
Float64RangeValidator float64 rangefloat min, max Inclusive float64 range.
MinFloat64Validator float64 minfloat min Float64 greater than or equal to min.
MaxFloat64Validator float64 maxfloat max Float64 less than or equal to max.
NonNegativeFloat64Validator float64 posfloat - Float64 is non-negative.
NonPositiveFloat64Validator float64 negfloat - Float64 is non-positive.
NonZeroFloat64Validator float64 !zerofloat (alias: nonzerofloat) - Float64 is not zero.
OneOfFloat64Validator float64 oneoffloat values Float64 is in values (pipe-separated list).
Strings
UrlValidator string url - Valid URL (absolute).
EmailValidator string email - Valid email address.
NonEmptyStringValidator string !empty (alias: nonempty) - String is not empty.
MinLengthValidator string min size String length >= size.
MaxLengthValidator string max size String length <= size.
LengthRangeValidator string len min, max String length in inclusive range.
RegexValidator string regex pattern String matches regex.
PrefixValidator string prefix value String has prefix.
SuffixValidator string suffix value String has suffix.
ContainsValidator string contains value String contains substring.
OneOfStringValidator string oneof values String is in values (pipe-separated list).
AlphaNumericValidator string alphanum - String is alphanumeric.
MACAddressValidator string mac - Valid MAC address.
IpValidator string ip - Valid IP address.
IPv4Validator string ipv4 - Valid IPv4 address.
IPv6Validator string ipv6 - Valid IPv6 address.
HostnameValidator string hostname - Valid hostname.
IPCIDRValidator string cidr - Valid CIDR notation.
UUIDValidator string uuid version (4) RFC 4122 UUID with optional version.
Base64Validator string base64 - Valid base64 (standard or raw).
HexValidator string hex - Valid hex string (optional 0x).
XMLValidator string xml - Well-formed XML with at least one element.
JSONValidator string json - Valid JSON.
TimeValidator string time format (RFC3339) Valid time for layout (built-in names or raw layout).
Time
NonZeroTimeValidator time.Time !zerotime (alias: nonzerotime) - Time is not zero.
TimeBeforeValidator time.Time beforetime before Time is before the configured time (RFC3339).
TimeAfterValidator time.Time aftertime after Time is after the configured time (RFC3339).
TimeBetweenValidator time.Time betweentime start, end Time is within the inclusive range (RFC3339).
Duration
PositiveDurationValidator time.Duration posduration - Duration is positive.
NonZeroDurationValidator time.Duration !zeroduration (alias: nonzeroduration) - Duration is not zero.
IP
NonZeroIPValidator net.IP !zeroip (alias: nonzeroip) - IP is not zero or unspecified.
IPRangeValidator net.IP iprange start, end IP is within the inclusive range.
URL
NonZeroURLValidator url.URL !zerourl (alias: nonzerourl) - URL is not zero.

License

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

Documentation

Overview

Package valex provides generic validators and tag-based validation directives.

It supports two primary workflows:

  1. Programmatic validation using Validator or ValidatorFunc along with ValidatedValue for guarded assignment.
  2. Struct tag validation using the "val" tag and ValidateStruct. You can pass additional tagex.Tag values to ValidateStruct to process multiple tags in a single pass.

For HTTP form binding, FormValidator parses requests and binds "field" tags before running validation, and ValidateForm provides a convenience wrapper with HTTP status mapping.

The built-in directives cover common validations (ranges, lengths, URLs, emails, IPs, JSON/XML, and regex). You can extend tag validation by registering custom directives with RegisterDirective.

Index

Constants

This section is empty.

Variables

View Source
var ErrFieldRequired = errors.New("field is required")

Functions

func BindFormValues

func BindFormValues(dst any, values url.Values) error

BindFormValues binds url.Values into a struct pointer using "field" tags.

func FormStatus

func FormStatus(err error) int

FormStatus maps validation errors to HTTP status codes.

func MustValidate

func MustValidate[T any](val T, v Validator[T]) T

MustValidate validates a value or panics if validation fails.

func RegisterDirective

func RegisterDirective[T any](d tagex.Directive[T])

RegisterDirective registers a directive for use with the "val" struct tag.

func ValidateForm

func ValidateForm(r *http.Request, dst any) (bool, error)

ValidateForm wraps NewFormValidator + Validate and returns a FormError on failure.

func ValidateStruct

func ValidateStruct(data interface{}, tags ...*tagex.Tag) (bool, error)

ValidateStruct validates struct fields using the "val" tag directives. Additional tagex.Tag values can be provided to process more tags in the same pass.

Types

type AlphaNumericValidator

type AlphaNumericValidator struct{}

AlphaNumericValidator validates that a string contains only alphanumeric characters.

func (*AlphaNumericValidator) Handle

func (v *AlphaNumericValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*AlphaNumericValidator) Mode

Mode returns the directive evaluation mode.

func (*AlphaNumericValidator) Name

func (v *AlphaNumericValidator) Name() string

Name returns the directive identifier.

func (*AlphaNumericValidator) Validate

func (v *AlphaNumericValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is alphanumeric.

type Base64Validator

type Base64Validator struct{}

Base64Validator validates that a string is valid base64.

func (*Base64Validator) Handle

func (v *Base64Validator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*Base64Validator) Mode

Mode returns the directive evaluation mode.

func (*Base64Validator) Name

func (v *Base64Validator) Name() string

Name returns the directive identifier.

func (*Base64Validator) Validate

func (v *Base64Validator) Validate(val string) (ok bool, err error)

Validate checks whether the value is base64 encoded.

type CmpRangeValidator

type CmpRangeValidator[T cmp.Ordered] struct {
	Min T
	Max T
}

CmpRangeValidator validates that a value is within an inclusive range.

func (*CmpRangeValidator[T]) Validate

func (v *CmpRangeValidator[T]) Validate(val T) (ok bool, err error)

Validate checks whether the value is within the configured range.

type CompositeValidator

type CompositeValidator[T cmp.Ordered] struct {
	Validators []Validator[T]
}

CompositeValidator validates a value by running multiple validators in order.

func (*CompositeValidator[T]) Validate

func (cv *CompositeValidator[T]) Validate(val T) (ok bool, err error)

Validate checks the value against each validator in order.

type ContainsValidator

type ContainsValidator struct {
	Value string `param:"value"`
}

ContainsValidator validates that a string contains a substring.

func (*ContainsValidator) Handle

func (v *ContainsValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*ContainsValidator) Mode

Mode returns the directive evaluation mode.

func (*ContainsValidator) Name

func (v *ContainsValidator) Name() string

Name returns the directive identifier.

func (*ContainsValidator) Validate

func (v *ContainsValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value contains the configured substring.

type EmailValidator

type EmailValidator struct{}

EmailValidator validates that a string is a valid email address.

func (*EmailValidator) Handle

func (v *EmailValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*EmailValidator) Mode

Mode returns the directive evaluation mode.

func (*EmailValidator) Name

func (v *EmailValidator) Name() string

Name returns the directive identifier.

func (*EmailValidator) Validate

func (v *EmailValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid email address.

type Float64RangeValidator

type Float64RangeValidator struct {
	Min float64 `param:"min"`
	Max float64 `param:"max"`
}

Float64RangeValidator validates that a float64 is within an inclusive range.

func (*Float64RangeValidator) Handle

func (v *Float64RangeValidator) Handle(val float64) (float64, error)

Handle validates the value and returns it unchanged.

func (*Float64RangeValidator) Mode

Mode returns the directive evaluation mode.

func (*Float64RangeValidator) Name

func (v *Float64RangeValidator) Name() string

Name returns the directive identifier.

func (*Float64RangeValidator) Validate

func (v *Float64RangeValidator) Validate(val float64) (ok bool, err error)

Validate checks whether the value is within the configured range.

type FormError

type FormError struct {
	Status int
	Err    error
}

FormError wraps a validation error with an HTTP status code.

func (*FormError) Error

func (e *FormError) Error() string

func (*FormError) StatusCode

func (e *FormError) StatusCode() int

StatusCode returns the associated HTTP status code.

func (*FormError) Unwrap

func (e *FormError) Unwrap() error

type FormValidator

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

func NewFormValidator

func NewFormValidator(r *http.Request) (*FormValidator, error)

NewFormValidator parses the request and prepares a validator. ParseForm handles both POST bodies and URL query parameters, so GET requests with query values are supported.

func (*FormValidator) Validate

func (v *FormValidator) Validate(dst any) (bool, error)

Validate binds form values into dst and validates "val" tags.

type HexValidator

type HexValidator struct{}

HexValidator validates that a string is valid hex.

func (*HexValidator) Handle

func (v *HexValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*HexValidator) Mode

func (v *HexValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*HexValidator) Name

func (v *HexValidator) Name() string

Name returns the directive identifier.

func (*HexValidator) Validate

func (v *HexValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a hex string.

type HostnameValidator

type HostnameValidator struct{}

HostnameValidator validates that a string is a valid hostname.

func (*HostnameValidator) Handle

func (v *HostnameValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*HostnameValidator) Mode

Mode returns the directive evaluation mode.

func (*HostnameValidator) Name

func (v *HostnameValidator) Name() string

Name returns the directive identifier.

func (*HostnameValidator) Validate

func (v *HostnameValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid hostname.

type IPCIDRValidator

type IPCIDRValidator struct{}

IPCIDRValidator validates that a string is a valid CIDR notation.

func (*IPCIDRValidator) Handle

func (v *IPCIDRValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*IPCIDRValidator) Mode

Mode returns the directive evaluation mode.

func (*IPCIDRValidator) Name

func (v *IPCIDRValidator) Name() string

Name returns the directive identifier.

func (*IPCIDRValidator) Validate

func (v *IPCIDRValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid CIDR.

type IPRangeValidator

type IPRangeValidator struct {
	Start net.IP `param:"start"`
	End   net.IP `param:"end"`
}

IPRangeValidator validates that a net.IP is within an inclusive range.

func (*IPRangeValidator) ConvertParam

func (v *IPRangeValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the start/end parameters.

func (*IPRangeValidator) Handle

func (v *IPRangeValidator) Handle(val net.IP) (net.IP, error)

Handle validates the value and returns it unchanged.

func (*IPRangeValidator) Mode

Mode returns the directive evaluation mode.

func (*IPRangeValidator) Name

func (v *IPRangeValidator) Name() string

Name returns the directive identifier.

func (*IPRangeValidator) Validate

func (v *IPRangeValidator) Validate(val net.IP) (ok bool, err error)

Validate checks whether the value is within the configured range.

type IPv4Validator

type IPv4Validator struct{}

IPv4Validator validates that a string is a valid IPv4 address.

func (*IPv4Validator) Handle

func (v *IPv4Validator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*IPv4Validator) Mode

func (v *IPv4Validator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*IPv4Validator) Name

func (v *IPv4Validator) Name() string

Name returns the directive identifier.

func (*IPv4Validator) Validate

func (v *IPv4Validator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid IPv4 address.

type IPv6Validator

type IPv6Validator struct{}

IPv6Validator validates that a string is a valid IPv6 address.

func (*IPv6Validator) Handle

func (v *IPv6Validator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*IPv6Validator) Mode

func (v *IPv6Validator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*IPv6Validator) Name

func (v *IPv6Validator) Name() string

Name returns the directive identifier.

func (*IPv6Validator) Validate

func (v *IPv6Validator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid IPv6 address.

type IntRangeValidator

type IntRangeValidator struct {
	Min int `param:"min"`
	Max int `param:"max"`
}

IntRangeValidator validates that an int is within an inclusive range.

func (*IntRangeValidator) Handle

func (v *IntRangeValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*IntRangeValidator) Mode

Mode returns the directive evaluation mode.

func (*IntRangeValidator) Name

func (v *IntRangeValidator) Name() string

Name returns the directive identifier.

func (*IntRangeValidator) Validate

func (v *IntRangeValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value is within the configured range.

type IpValidator

type IpValidator struct{}

IpValidator validates that a string is a valid IP address.

func (*IpValidator) Handle

func (v *IpValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*IpValidator) Mode

func (v *IpValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*IpValidator) Name

func (v *IpValidator) Name() string

Name returns the directive identifier.

func (*IpValidator) Validate

func (v *IpValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid IP address.

type JSONValidator

type JSONValidator struct{}

JSONValidator validates that a string is valid JSON.

func (*JSONValidator) Handle

func (v *JSONValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*JSONValidator) Mode

func (v *JSONValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*JSONValidator) Name

func (v *JSONValidator) Name() string

Name returns the directive identifier.

func (*JSONValidator) Validate

func (v *JSONValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is valid JSON.

type LengthRangeValidator

type LengthRangeValidator struct {
	Min int `param:"min"`
	Max int `param:"max"`
}

LengthRangeValidator validates that a string length is within an inclusive range.

func (*LengthRangeValidator) Handle

func (v *LengthRangeValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*LengthRangeValidator) Mode

Mode returns the directive evaluation mode.

func (*LengthRangeValidator) Name

func (v *LengthRangeValidator) Name() string

Name returns the directive identifier.

func (*LengthRangeValidator) Validate

func (v *LengthRangeValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value length is within the configured range.

type MACAddressValidator

type MACAddressValidator struct{}

MACAddressValidator validates that a string is a valid MAC address.

func (*MACAddressValidator) Handle

func (v *MACAddressValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*MACAddressValidator) Mode

Mode returns the directive evaluation mode.

func (*MACAddressValidator) Name

func (v *MACAddressValidator) Name() string

Name returns the directive identifier.

func (*MACAddressValidator) Validate

func (v *MACAddressValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid MAC address.

type MaxFloat64Validator

type MaxFloat64Validator struct {
	Max float64 `param:"max"`
}

MaxFloat64Validator validates that a float64 is less than or equal to Max.

func (*MaxFloat64Validator) Handle

func (v *MaxFloat64Validator) Handle(val float64) (float64, error)

Handle validates the value and returns it unchanged.

func (*MaxFloat64Validator) Mode

Mode returns the directive evaluation mode.

func (*MaxFloat64Validator) Name

func (v *MaxFloat64Validator) Name() string

Name returns the directive identifier.

func (*MaxFloat64Validator) Validate

func (v *MaxFloat64Validator) Validate(val float64) (ok bool, err error)

Validate checks whether the value meets the maximum.

type MaxIntValidator

type MaxIntValidator struct {
	Max int `param:"max"`
}

MaxIntValidator validates that an int is less than or equal to Max.

func (*MaxIntValidator) Handle

func (v *MaxIntValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*MaxIntValidator) Mode

Mode returns the directive evaluation mode.

func (*MaxIntValidator) Name

func (v *MaxIntValidator) Name() string

Name returns the directive identifier.

func (*MaxIntValidator) Validate

func (v *MaxIntValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value meets the maximum.

type MaxLengthValidator

type MaxLengthValidator struct {
	Size int `param:"size"`
}

MaxLengthValidator validates that a string does not exceed a maximum length.

func (*MaxLengthValidator) Handle

func (v *MaxLengthValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*MaxLengthValidator) Mode

Mode returns the directive evaluation mode.

func (*MaxLengthValidator) Name

func (v *MaxLengthValidator) Name() string

Name returns the directive identifier.

func (*MaxLengthValidator) Validate

func (v *MaxLengthValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value does not exceed the maximum length.

type MinFloat64Validator

type MinFloat64Validator struct {
	Min float64 `param:"min"`
}

MinFloat64Validator validates that a float64 is greater than or equal to Min.

func (*MinFloat64Validator) Handle

func (v *MinFloat64Validator) Handle(val float64) (float64, error)

Handle validates the value and returns it unchanged.

func (*MinFloat64Validator) Mode

Mode returns the directive evaluation mode.

func (*MinFloat64Validator) Name

func (v *MinFloat64Validator) Name() string

Name returns the directive identifier.

func (*MinFloat64Validator) Validate

func (v *MinFloat64Validator) Validate(val float64) (ok bool, err error)

Validate checks whether the value meets the minimum.

type MinIntValidator

type MinIntValidator struct {
	Min int `param:"min"`
}

MinIntValidator validates that an int is greater than or equal to Min.

func (*MinIntValidator) Handle

func (v *MinIntValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*MinIntValidator) Mode

Mode returns the directive evaluation mode.

func (*MinIntValidator) Name

func (v *MinIntValidator) Name() string

Name returns the directive identifier.

func (*MinIntValidator) Validate

func (v *MinIntValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value meets the minimum.

type MinLengthValidator

type MinLengthValidator struct {
	Size int `param:"size"`
}

MinLengthValidator validates that a string meets a minimum length.

func (*MinLengthValidator) Handle

func (v *MinLengthValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*MinLengthValidator) Mode

Mode returns the directive evaluation mode.

func (*MinLengthValidator) Name

func (v *MinLengthValidator) Name() string

Name returns the directive identifier.

func (*MinLengthValidator) Validate

func (v *MinLengthValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value meets the minimum length.

type NonEmptyStringAliasValidator

type NonEmptyStringAliasValidator struct {
	NonEmptyStringValidator
}

NonEmptyStringAliasValidator provides the legacy "nonempty" tag.

func (*NonEmptyStringAliasValidator) Name

Name returns the directive identifier.

type NonEmptyStringValidator

type NonEmptyStringValidator struct{}

NonEmptyStringValidator validates that a string is not empty.

func (*NonEmptyStringValidator) Handle

func (v *NonEmptyStringValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*NonEmptyStringValidator) Mode

Mode returns the directive evaluation mode.

func (*NonEmptyStringValidator) Name

func (v *NonEmptyStringValidator) Name() string

Name returns the directive identifier.

func (*NonEmptyStringValidator) Validate

func (v *NonEmptyStringValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is non-empty.

type NonNegativeFloat64Validator

type NonNegativeFloat64Validator struct{}

NonNegativeFloat64Validator validates that a float64 is not negative.

func (*NonNegativeFloat64Validator) Handle

Handle validates the value and returns it unchanged.

func (*NonNegativeFloat64Validator) Mode

Mode returns the directive evaluation mode.

func (*NonNegativeFloat64Validator) Name

Name returns the directive identifier.

func (*NonNegativeFloat64Validator) Validate

func (v *NonNegativeFloat64Validator) Validate(val float64) (ok bool, err error)

Validate checks whether the value is non-negative.

type NonNegativeIntValidator

type NonNegativeIntValidator struct{}

NonNegativeIntValidator validates that an int is not negative.

func (*NonNegativeIntValidator) Handle

func (v *NonNegativeIntValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*NonNegativeIntValidator) Mode

Mode returns the directive evaluation mode.

func (*NonNegativeIntValidator) Name

func (v *NonNegativeIntValidator) Name() string

Name returns the directive identifier.

func (*NonNegativeIntValidator) Validate

func (v *NonNegativeIntValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value is non-negative.

type NonPositiveFloat64Validator

type NonPositiveFloat64Validator struct{}

NonPositiveFloat64Validator validates that a float64 is not positive.

func (*NonPositiveFloat64Validator) Handle

Handle validates the value and returns it unchanged.

func (*NonPositiveFloat64Validator) Mode

Mode returns the directive evaluation mode.

func (*NonPositiveFloat64Validator) Name

Name returns the directive identifier.

func (*NonPositiveFloat64Validator) Validate

func (v *NonPositiveFloat64Validator) Validate(val float64) (ok bool, err error)

Validate checks whether the value is non-positive.

type NonPositiveIntValidator

type NonPositiveIntValidator struct{}

NonPositiveIntValidator validates that an int is not positive.

func (*NonPositiveIntValidator) Handle

func (v *NonPositiveIntValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*NonPositiveIntValidator) Mode

Mode returns the directive evaluation mode.

func (*NonPositiveIntValidator) Name

func (v *NonPositiveIntValidator) Name() string

Name returns the directive identifier.

func (*NonPositiveIntValidator) Validate

func (v *NonPositiveIntValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value is non-positive.

type NonZeroDurationAliasValidator

type NonZeroDurationAliasValidator struct {
	NonZeroDurationValidator
}

NonZeroDurationAliasValidator provides the "nonzeroduration" tag.

func (*NonZeroDurationAliasValidator) Name

Name returns the directive identifier.

type NonZeroDurationValidator

type NonZeroDurationValidator struct{}

NonZeroDurationValidator validates that a time.Duration is not zero.

func (*NonZeroDurationValidator) Handle

Handle validates the value and returns it unchanged.

func (*NonZeroDurationValidator) Mode

Mode returns the directive evaluation mode.

func (*NonZeroDurationValidator) Name

func (v *NonZeroDurationValidator) Name() string

Name returns the directive identifier.

func (*NonZeroDurationValidator) Validate

func (v *NonZeroDurationValidator) Validate(val time.Duration) (ok bool, err error)

Validate checks whether the value is non-zero.

type NonZeroFloat64AliasValidator

type NonZeroFloat64AliasValidator struct {
	NonZeroFloat64Validator
}

NonZeroFloat64AliasValidator provides the "nonzerofloat" tag.

func (*NonZeroFloat64AliasValidator) Name

Name returns the directive identifier.

type NonZeroFloat64Validator

type NonZeroFloat64Validator struct{}

NonZeroFloat64Validator validates that a float64 is not zero.

func (*NonZeroFloat64Validator) Handle

func (v *NonZeroFloat64Validator) Handle(val float64) (float64, error)

Handle validates the value and returns it unchanged.

func (*NonZeroFloat64Validator) Mode

Mode returns the directive evaluation mode.

func (*NonZeroFloat64Validator) Name

func (v *NonZeroFloat64Validator) Name() string

Name returns the directive identifier.

func (*NonZeroFloat64Validator) Validate

func (v *NonZeroFloat64Validator) Validate(val float64) (ok bool, err error)

Validate checks whether the value is non-zero.

type NonZeroIPAliasValidator

type NonZeroIPAliasValidator struct {
	NonZeroIPValidator
}

NonZeroIPAliasValidator provides the "nonzeroip" tag.

func (*NonZeroIPAliasValidator) Name

func (v *NonZeroIPAliasValidator) Name() string

Name returns the directive identifier.

type NonZeroIPValidator

type NonZeroIPValidator struct{}

NonZeroIPValidator validates that a net.IP is not zero or unspecified.

func (*NonZeroIPValidator) Handle

func (v *NonZeroIPValidator) Handle(val net.IP) (net.IP, error)

Handle validates the value and returns it unchanged.

func (*NonZeroIPValidator) Mode

Mode returns the directive evaluation mode.

func (*NonZeroIPValidator) Name

func (v *NonZeroIPValidator) Name() string

Name returns the directive identifier.

func (*NonZeroIPValidator) Validate

func (v *NonZeroIPValidator) Validate(val net.IP) (ok bool, err error)

Validate checks whether the value is non-zero.

type NonZeroIntAliasValidator

type NonZeroIntAliasValidator struct {
	NonZeroIntValidator
}

NonZeroIntAliasValidator provides the "nonzeroint" tag.

func (*NonZeroIntAliasValidator) Name

func (v *NonZeroIntAliasValidator) Name() string

Name returns the directive identifier.

type NonZeroIntValidator

type NonZeroIntValidator struct{}

NonZeroIntValidator validates that an int is not zero.

func (*NonZeroIntValidator) Handle

func (v *NonZeroIntValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*NonZeroIntValidator) Mode

Mode returns the directive evaluation mode.

func (*NonZeroIntValidator) Name

func (v *NonZeroIntValidator) Name() string

Name returns the directive identifier.

func (*NonZeroIntValidator) Validate

func (v *NonZeroIntValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value is non-zero.

type NonZeroTimeAliasValidator

type NonZeroTimeAliasValidator struct {
	NonZeroTimeValidator
}

NonZeroTimeAliasValidator provides the legacy "nonzerotime" tag.

func (*NonZeroTimeAliasValidator) Name

Name returns the directive identifier.

type NonZeroTimeValidator

type NonZeroTimeValidator struct{}

NonZeroTimeValidator validates that a time.Time is not zero.

func (*NonZeroTimeValidator) Handle

func (v *NonZeroTimeValidator) Handle(val time.Time) (time.Time, error)

Handle validates the value and returns it unchanged.

func (*NonZeroTimeValidator) Mode

Mode returns the directive evaluation mode.

func (*NonZeroTimeValidator) Name

func (v *NonZeroTimeValidator) Name() string

Name returns the directive identifier.

func (*NonZeroTimeValidator) Validate

func (v *NonZeroTimeValidator) Validate(val time.Time) (ok bool, err error)

Validate checks whether the value is non-zero.

type NonZeroURLAliasValidator

type NonZeroURLAliasValidator struct {
	NonZeroURLValidator
}

NonZeroURLAliasValidator provides the "nonzerourl" tag.

func (*NonZeroURLAliasValidator) Name

func (v *NonZeroURLAliasValidator) Name() string

Name returns the directive identifier.

type NonZeroURLValidator

type NonZeroURLValidator struct{}

NonZeroURLValidator validates that a url.URL is not zero.

func (*NonZeroURLValidator) Handle

func (v *NonZeroURLValidator) Handle(val url.URL) (url.URL, error)

Handle validates the value and returns it unchanged.

func (*NonZeroURLValidator) Mode

Mode returns the directive evaluation mode.

func (*NonZeroURLValidator) Name

func (v *NonZeroURLValidator) Name() string

Name returns the directive identifier.

func (*NonZeroURLValidator) Validate

func (v *NonZeroURLValidator) Validate(val url.URL) (ok bool, err error)

Validate checks whether the value is non-zero.

type NonZeroValidator

type NonZeroValidator[T any] struct{}

NonZeroValidator validates that a value is not the zero value for its type.

func (*NonZeroValidator[T]) Validate

func (v *NonZeroValidator[T]) Validate(val T) (ok bool, err error)

Validate checks whether the value is non-zero.

type OneOfFloat64Validator

type OneOfFloat64Validator struct {
	Values []float64 `param:"values"`
}

OneOfFloat64Validator validates that a float64 matches one of the configured values.

func (*OneOfFloat64Validator) ConvertParam

func (v *OneOfFloat64Validator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the values parameter.

func (*OneOfFloat64Validator) Handle

func (v *OneOfFloat64Validator) Handle(val float64) (float64, error)

Handle validates the value and returns it unchanged.

func (*OneOfFloat64Validator) Mode

Mode returns the directive evaluation mode.

func (*OneOfFloat64Validator) Name

func (v *OneOfFloat64Validator) Name() string

Name returns the directive identifier.

func (*OneOfFloat64Validator) Validate

func (v *OneOfFloat64Validator) Validate(val float64) (ok bool, err error)

Validate checks whether the value is in the configured set.

type OneOfIntValidator

type OneOfIntValidator struct {
	Values []int `param:"values"`
}

OneOfIntValidator validates that an int matches one of the configured values.

func (*OneOfIntValidator) ConvertParam

func (v *OneOfIntValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the values parameter.

func (*OneOfIntValidator) Handle

func (v *OneOfIntValidator) Handle(val int) (int, error)

Handle validates the value and returns it unchanged.

func (*OneOfIntValidator) Mode

Mode returns the directive evaluation mode.

func (*OneOfIntValidator) Name

func (v *OneOfIntValidator) Name() string

Name returns the directive identifier.

func (*OneOfIntValidator) Validate

func (v *OneOfIntValidator) Validate(val int) (ok bool, err error)

Validate checks whether the value is in the configured set.

type OneOfStringValidator

type OneOfStringValidator struct {
	Values []string `param:"values"`
}

OneOfStringValidator validates that a string matches one of the configured values.

func (*OneOfStringValidator) ConvertParam

func (v *OneOfStringValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the values parameter.

func (*OneOfStringValidator) Handle

func (v *OneOfStringValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*OneOfStringValidator) Mode

Mode returns the directive evaluation mode.

func (*OneOfStringValidator) Name

func (v *OneOfStringValidator) Name() string

Name returns the directive identifier.

func (*OneOfStringValidator) Validate

func (v *OneOfStringValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is in the configured set.

type PositiveDurationValidator

type PositiveDurationValidator struct{}

PositiveDurationValidator validates that a time.Duration is positive.

func (*PositiveDurationValidator) Handle

Handle validates the value and returns it unchanged.

func (*PositiveDurationValidator) Mode

Mode returns the directive evaluation mode.

func (*PositiveDurationValidator) Name

Name returns the directive identifier.

func (*PositiveDurationValidator) Validate

func (v *PositiveDurationValidator) Validate(val time.Duration) (ok bool, err error)

Validate checks whether the value is positive.

type PrefixValidator

type PrefixValidator struct {
	Value string `param:"value"`
}

PrefixValidator validates that a string has a given prefix.

func (*PrefixValidator) Handle

func (v *PrefixValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*PrefixValidator) Mode

Mode returns the directive evaluation mode.

func (*PrefixValidator) Name

func (v *PrefixValidator) Name() string

Name returns the directive identifier.

func (*PrefixValidator) Validate

func (v *PrefixValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value has the configured prefix.

type RegexValidator

type RegexValidator struct {
	Pattern *regexp.Regexp `param:"pattern"`
}

RegexValidator validates that a string matches a regular expression.

func (*RegexValidator) ConvertParam

func (v *RegexValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam compiles the regex pattern parameter.

func (*RegexValidator) Handle

func (v *RegexValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*RegexValidator) Mode

Mode returns the directive evaluation mode.

func (*RegexValidator) Name

func (v *RegexValidator) Name() string

Name returns the directive identifier.

func (*RegexValidator) Validate

func (v *RegexValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value matches the configured pattern.

type SuffixValidator

type SuffixValidator struct {
	Value string `param:"value"`
}

SuffixValidator validates that a string has a given suffix.

func (*SuffixValidator) Handle

func (v *SuffixValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*SuffixValidator) Mode

Mode returns the directive evaluation mode.

func (*SuffixValidator) Name

func (v *SuffixValidator) Name() string

Name returns the directive identifier.

func (*SuffixValidator) Validate

func (v *SuffixValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value has the configured suffix.

type TimeAfterValidator

type TimeAfterValidator struct {
	After time.Time `param:"after"`
}

TimeAfterValidator validates that a time.Time is after the configured time.

func (*TimeAfterValidator) ConvertParam

func (v *TimeAfterValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the after parameter.

func (*TimeAfterValidator) Handle

func (v *TimeAfterValidator) Handle(val time.Time) (time.Time, error)

Handle validates the value and returns it unchanged.

func (*TimeAfterValidator) Mode

Mode returns the directive evaluation mode.

func (*TimeAfterValidator) Name

func (v *TimeAfterValidator) Name() string

Name returns the directive identifier.

func (*TimeAfterValidator) Validate

func (v *TimeAfterValidator) Validate(val time.Time) (ok bool, err error)

Validate checks whether the value is after the configured time.

type TimeBeforeValidator

type TimeBeforeValidator struct {
	Before time.Time `param:"before"`
}

TimeBeforeValidator validates that a time.Time is before the configured time.

func (*TimeBeforeValidator) ConvertParam

func (v *TimeBeforeValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the before parameter.

func (*TimeBeforeValidator) Handle

func (v *TimeBeforeValidator) Handle(val time.Time) (time.Time, error)

Handle validates the value and returns it unchanged.

func (*TimeBeforeValidator) Mode

Mode returns the directive evaluation mode.

func (*TimeBeforeValidator) Name

func (v *TimeBeforeValidator) Name() string

Name returns the directive identifier.

func (*TimeBeforeValidator) Validate

func (v *TimeBeforeValidator) Validate(val time.Time) (ok bool, err error)

Validate checks whether the value is before the configured time.

type TimeBetweenValidator

type TimeBetweenValidator struct {
	Start time.Time `param:"start"`
	End   time.Time `param:"end"`
}

TimeBetweenValidator validates that a time.Time is within an inclusive range.

func (*TimeBetweenValidator) ConvertParam

func (v *TimeBetweenValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the start/end parameters.

func (*TimeBetweenValidator) Handle

func (v *TimeBetweenValidator) Handle(val time.Time) (time.Time, error)

Handle validates the value and returns it unchanged.

func (*TimeBetweenValidator) Mode

Mode returns the directive evaluation mode.

func (*TimeBetweenValidator) Name

func (v *TimeBetweenValidator) Name() string

Name returns the directive identifier.

func (*TimeBetweenValidator) Validate

func (v *TimeBetweenValidator) Validate(val time.Time) (ok bool, err error)

Validate checks whether the value is within the configured range.

type TimeValidator

type TimeValidator struct {
	Format string `param:"format,required=false"`
}

TimeValidator validates that a string matches a time layout. If Format is empty, time.RFC3339 is used.

func (*TimeValidator) ConvertParam

func (v *TimeValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam maps well-known time layout names or accepts a raw layout string.

func (*TimeValidator) Handle

func (v *TimeValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*TimeValidator) Mode

func (v *TimeValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*TimeValidator) Name

func (v *TimeValidator) Name() string

Name returns the directive identifier.

func (*TimeValidator) Validate

func (v *TimeValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value matches the configured layout.

type UUIDValidator

type UUIDValidator struct {
	Version int `param:"version,required=false"`
}

UUIDValidator validates that a string is a RFC 4122 UUID. If Version is 0, version 4 is assumed.

func (*UUIDValidator) ConvertParam

func (v *UUIDValidator) ConvertParam(field reflect.StructField, fieldValue reflect.Value, raw string) error

ConvertParam parses the version parameter.

func (*UUIDValidator) Handle

func (v *UUIDValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*UUIDValidator) Mode

func (v *UUIDValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*UUIDValidator) Name

func (v *UUIDValidator) Name() string

Name returns the directive identifier.

func (*UUIDValidator) Validate

func (v *UUIDValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a UUID.

type UrlValidator

type UrlValidator struct{}

UrlValidator validates that a string is a valid URL.

func (*UrlValidator) Handle

func (v *UrlValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*UrlValidator) Mode

func (v *UrlValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*UrlValidator) Name

func (v *UrlValidator) Name() string

Name returns the directive identifier.

func (*UrlValidator) Validate

func (v *UrlValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is a valid URL.

type ValidatedValue

type ValidatedValue[T cmp.Ordered] struct {
	Validator Validator[T]
	// contains filtered or unexported fields
}

ValidatedValue stores a value and validates updates with the provided Validator.

func (*ValidatedValue[T]) Get

func (v *ValidatedValue[T]) Get() T

Get returns the stored value.

func (*ValidatedValue[T]) Set

func (v *ValidatedValue[T]) Set(val T) error

Set validates and stores the value.

func (*ValidatedValue[T]) String

func (v *ValidatedValue[T]) String() string

String returns the string representation of the stored value.

type Validator

type Validator[T any] interface {
	Validate(val T) (ok bool, err error)
}

Validator defines the behavior for validating a value of type T.

type ValidatorFunc

type ValidatorFunc[T any] func(val T) (ok bool, err error)

ValidatorFunc adapts a function to the Validator interface.

func (ValidatorFunc[T]) Validate

func (p ValidatorFunc[T]) Validate(val T) (ok bool, err error)

Validate calls the underlying function.

type XMLValidator

type XMLValidator struct{}

XMLValidator validates that a string is well-formed XML with at least one element.

func (*XMLValidator) Handle

func (v *XMLValidator) Handle(val string) (string, error)

Handle validates the value and returns it unchanged.

func (*XMLValidator) Mode

func (v *XMLValidator) Mode() tagex.DirectiveMode

Mode returns the directive evaluation mode.

func (*XMLValidator) Name

func (v *XMLValidator) Name() string

Name returns the directive identifier.

func (*XMLValidator) Validate

func (v *XMLValidator) Validate(val string) (ok bool, err error)

Validate checks whether the value is valid XML with at least one element.

Jump to

Keyboard shortcuts

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