validator

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 9 Imported by: 0

README

validator

import "github.com/brpaz/lib-go/validator"

Package validator provides a lightweight, composable field validator.

Build a Validator, call Validator.Field for each input field with one or more Rule functions, then call Validator.Result to retrieve a \*ValidationError (nil when all fields pass).

Example:

v := validator.New()
v.Field("email", req.Email, validator.Required(), validator.Email())
v.Field("age", req.Age, validator.Gte(18))
if err := v.Result(); err != nil {
    // err.Fields contains per-field details
}

Index

type ErrCode

ErrCode is a machine-readable validation error code.

type ErrCode string

Field-level validation codes.

const (
    ErrRequired  ErrCode = "required"
    ErrInvalid   ErrCode = "invalid"
    ErrMinLength ErrCode = "min_length"
    ErrMaxLength ErrCode = "max_length"
    ErrMin       ErrCode = "min"
    ErrMax       ErrCode = "max"
    ErrDuplicate ErrCode = "duplicate"
)

type FieldError

FieldError describes a validation failure for a single field.

type FieldError struct {
    Field   string
    Code    ErrCode
    Message string
    Params  map[string]any
}

func (FieldError) Error
func (e FieldError) Error() string

Error implements the error interface.

type Rule

Rule is a validation function. Returns nil when the value is valid. On failure, return a *RuleError to carry a code and message.

type Rule func(value any) error

func Between
func Between(min, max float64) Rule

Between fails when value is outside [min, max] (inclusive). Returns ErrMin when below min, ErrMax when above max.

func Email
func Email() Rule

Email fails when the value is not a valid email address. Display-name format ("John <user@example.com>") is rejected; only bare addresses pass.

func Gt
func Gt(n float64) Rule

Gt fails when the numeric value is not greater than n.

func Gte
func Gte(n float64) Rule

Gte fails when the numeric value is less than n.

func HasSpecialChar
func HasSpecialChar() Rule

HasSpecialChar fails when the value contains no non-alphanumeric character.

func Lt
func Lt(n float64) Rule

Lt fails when the numeric value is not less than n.

func Lte
func Lte(n float64) Rule

Lte fails when the numeric value exceeds n.

func Matches
func Matches(re *regexp.Regexp, message ...string) Rule

Matches fails when the value does not match re. Compile the regexp once at package or init level, not inside a handler. An optional message overrides the default "invalid format" error text.

func MaxLength
func MaxLength(n int) Rule

MaxLength fails when the UTF-8 rune count of value exceeds n.

func MinLength
func MinLength(n int) Rule

MinLength fails when the UTF-8 rune count of value is less than n.

func NonNegative
func NonNegative() Rule

NonNegative fails when value is less than 0.

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

OneOf fails when value is not among the provided allowed values.

func Optional
func Optional(rules ...Rule) Rule

Optional wraps rules and skips them when value is nil or whitespace-only. Non-empty values are passed through all rules in order; first failure stops.

func Positive
func Positive() Rule

Positive fails when value is not greater than 0.

func Required
func Required() Rule

Required fails when value is nil, empty, or whitespace-only. Non-nil, non-string values are considered present and pass.

func URL
func URL() Rule

URL fails when the value is not a valid absolute URL (scheme and host required).

func UUID
func UUID() Rule

UUID fails when the value is not a valid RFC 4122 UUID.

type RuleError

RuleError is returned by a Rule when validation fails. Callers that invoke rules directly can use errors.As to retrieve the code and params.

type RuleError struct {
    Code    ErrCode
    Message string
    Params  map[string]any
}

func (*RuleError) Error
func (e *RuleError) Error() string

Error implements the error interface.

type ValidationError

ValidationError is returned by Validator.Result when one or more fields failed validation.

type ValidationError struct {
    Message string
    Fields  []FieldError
}

func (*ValidationError) Error
func (e *ValidationError) Error() string

Error implements the error interface.

type Validator

Validator accumulates field errors for a request payload.

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

func New
func New() *Validator

New creates a new Validator.

func (*Validator) Field
func (v *Validator) Field(fieldName string, value any, rules ...Rule)

Field runs rules against value in order, recording the first failure for fieldName. Subsequent rules are skipped once a failure is found. Rules that return a plain error (not *RuleError) are recorded with CodeInvalid.

func (*Validator) Result
func (v *Validator) Result() *ValidationError

Result returns nil if no errors were recorded, or a *ValidationError with all field errors.

Generated by gomarkdoc

Documentation

Overview

Package validator provides a lightweight, composable field validator.

Build a Validator, call Validator.Field for each input field with one or more Rule functions, then call Validator.Result to retrieve a *ValidationError (nil when all fields pass).

Example:

v := validator.New()
v.Field("email", req.Email, validator.Required(), validator.Email())
v.Field("age", req.Age, validator.Gte(18))
if err := v.Result(); err != nil {
    // err.Fields contains per-field details
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrCode

type ErrCode string

ErrCode is a machine-readable validation error code.

const (
	ErrRequired  ErrCode = "required"
	ErrInvalid   ErrCode = "invalid"
	ErrMinLength ErrCode = "min_length"
	ErrMaxLength ErrCode = "max_length"
	ErrMin       ErrCode = "min"
	ErrMax       ErrCode = "max"
	ErrDuplicate ErrCode = "duplicate"
)

Field-level validation codes.

type FieldError

type FieldError struct {
	Field   string
	Code    ErrCode
	Message string
	Params  map[string]any
}

FieldError describes a validation failure for a single field.

func (FieldError) Error

func (e FieldError) Error() string

Error implements the error interface.

type Rule

type Rule func(value any) error

Rule is a validation function. Returns nil when the value is valid. On failure, return a *RuleError to carry a code and message.

func Between

func Between(min, max float64) Rule

Between fails when value is outside [min, max] (inclusive). Returns ErrMin when below min, ErrMax when above max.

func Email

func Email() Rule

Email fails when the value is not a valid email address. Display-name format ("John <user@example.com>") is rejected; only bare addresses pass.

func Gt

func Gt(n float64) Rule

Gt fails when the numeric value is not greater than n.

func Gte

func Gte(n float64) Rule

Gte fails when the numeric value is less than n.

func HasSpecialChar

func HasSpecialChar() Rule

HasSpecialChar fails when the value contains no non-alphanumeric character.

func Lt

func Lt(n float64) Rule

Lt fails when the numeric value is not less than n.

func Lte

func Lte(n float64) Rule

Lte fails when the numeric value exceeds n.

func Matches

func Matches(re *regexp.Regexp, message ...string) Rule

Matches fails when the value does not match re. Compile the regexp once at package or init level, not inside a handler. An optional message overrides the default "invalid format" error text.

func MaxLength

func MaxLength(n int) Rule

MaxLength fails when the UTF-8 rune count of value exceeds n.

func MinLength

func MinLength(n int) Rule

MinLength fails when the UTF-8 rune count of value is less than n.

func NonNegative

func NonNegative() Rule

NonNegative fails when value is less than 0.

func OneOf

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

OneOf fails when value is not among the provided allowed values.

func Optional

func Optional(rules ...Rule) Rule

Optional wraps rules and skips them when value is nil or whitespace-only. Non-empty values are passed through all rules in order; first failure stops.

func Positive

func Positive() Rule

Positive fails when value is not greater than 0.

func Required

func Required() Rule

Required fails when value is nil, empty, or whitespace-only. Non-nil, non-string values are considered present and pass.

func URL

func URL() Rule

URL fails when the value is not a valid absolute URL (scheme and host required).

func UUID

func UUID() Rule

UUID fails when the value is not a valid RFC 4122 UUID.

type RuleError

type RuleError struct {
	Code    ErrCode
	Message string
	Params  map[string]any
}

RuleError is returned by a Rule when validation fails. Callers that invoke rules directly can use errors.As to retrieve the code and params.

func (*RuleError) Error

func (e *RuleError) Error() string

Error implements the error interface.

type ValidationError

type ValidationError struct {
	Message string
	Fields  []FieldError
}

ValidationError is returned by Validator.Result when one or more fields failed validation.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type Validator

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

Validator accumulates field errors for a request payload.

func New

func New() *Validator

New creates a new Validator.

func (*Validator) Field

func (v *Validator) Field(fieldName string, value any, rules ...Rule)

Field runs rules against value in order, recording the first failure for fieldName. Subsequent rules are skipped once a failure is found. Rules that return a plain error (not *RuleError) are recorded with CodeInvalid.

func (*Validator) Result

func (v *Validator) Result() *ValidationError

Result returns nil if no errors were recorded, or a *ValidationError with all field errors.

Jump to

Keyboard shortcuts

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