validation

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2025 License: BSD-2-Clause Imports: 4 Imported by: 6

README

Validation

Go Reference CI Go Report Card

A Go validation library that provides functional composition for validation rules using the HasValidation interface pattern.

Features

  • Functional Composition: Combine validators using All (AND logic) and Any (OR logic)
  • Interface-Based: All validators implement HasValidation with Validate(ctx context.Context) error
  • Context-Aware: All validation functions accept context for cancellation and timeout support
  • Error Wrapping: Consistent error handling using github.com/bborbe/errors
  • Comprehensive Validators: Basic, string, slice, length, and conditional validators

Installation

go get github.com/bborbe/validation

Quick Start

package main

import (
    "context"
    "fmt"
    "github.com/bborbe/validation"
)

func main() {
    ctx := context.Background()
    
    // Basic validation
    validator := validation.All{
        validation.NotNil(someValue),
        validation.NotEmptyString(someString),
        validation.LengthGe(someSlice, 1),
    }
    
    if err := validator.Validate(ctx); err != nil {
        fmt.Printf("Validation failed: %v\n", err)
        return
    }
    
    fmt.Println("Validation passed!")
}

Available Validators

Basic Validators
  • NotNil(value) - Validates that a value is not nil
  • Nil(value) - Validates that a value is nil
  • True(value) - Validates that a boolean is true
  • False(value) - Validates that a boolean is false
  • Equal(actual, expected) - Validates equality
String/Slice Validators
  • NotEmptyString(value) - Validates that a string is not empty
  • NotEmptySlice(value) - Validates that a slice is not empty
Length Validators
  • LengthEqual(value, length) - Validates exact length
  • LengthGt(value, length) - Validates length greater than
  • LengthGe(value, length) - Validates length greater than or equal
  • LengthLt(value, length) - Validates length less than
  • LengthLe(value, length) - Validates length less than or equal
Logical Operators
  • All{validators...} - All validators must pass (AND logic)
  • Any{validators...} - At least one validator must pass (OR logic)
  • Either{validator1, validator2} - Exactly one validator must pass
  • Not{validator} - Inverts validation result
Conditional Validators
  • NilOrValid(value, validator) - Pass if nil or if validator passes
  • NotNilAndValid(value, validator) - Pass if not nil and validator passes

Usage Examples

Combining Validators
validator := validation.All{
    validation.NotNil(user),
    validation.NotEmptyString(user.Name),
    validation.Any{
        validation.NotEmptyString(user.Email),
        validation.NotEmptyString(user.Phone),
    },
}
Custom Validators
customValidator := validation.HasValidationFunc(func(ctx context.Context) error {
    if someCondition {
        return validation.NewError("custom validation failed")
    }
    return nil
})

API Documentation

For complete API documentation, visit pkg.go.dev.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (make test)
  4. Run checks (make check)
  5. Commit your changes (git commit -am 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development

# Install dependencies
make ensure

# Run tests
make test

# Run all checks (format, generate, test, check, addlicense)
make precommit

License

This project is licensed under the BSD 2-Clause License - see the LICENSE file for details.

Documentation

Overview

Package validation provides functional composition for validation rules using the HasValidation interface pattern.

The core principle is that all validators implement the HasValidation interface with a single method:

Validate(ctx context.Context) error

This allows for consistent composition of validation rules using logical operators like All and Any.

Basic usage:

validator := validation.All{
	validation.NotNil(user),
	validation.NotEmptyString(user.Name),
	validation.LengthGe(user.Email, 1),
}

if err := validator.Validate(ctx); err != nil {
	// Handle validation error
}

The package provides validators for common scenarios:

  • Basic validators: NotNil, Nil, True, False, Equal
  • String/slice validators: NotEmptyString, NotEmptySlice
  • Length validators: LengthEqual, LengthGt, LengthGe, LengthLt, LengthLe
  • Logical operators: All, Any, Either, Not
  • Conditional validators: NilOrValid, NotNilAndValid

All validation errors are wrapped using github.com/bborbe/errors for consistent error handling.

Index

Constants

This section is empty.

Variables

View Source
var Error = stderrors.New("validation error")

Error is the base error used by all validation functions. All validation errors are wrapped using this error for consistent error handling.

Functions

This section is empty.

Types

type All

type All []HasValidation

All represents a logical AND operation for multiple validators. All validators must pass for the validation to succeed.

func (All) Validate

func (l All) Validate(ctx context.Context) error

Validate executes all validators and returns an error if any validator fails. It stops at the first validation failure and returns that error wrapped with context.

type Any

type Any []HasValidation

Any represents a logical OR operation for multiple validators. At least one validator must pass for the validation to succeed.

func (Any) Validate

func (l Any) Validate(ctx context.Context) error

Validate executes validators until one passes or all fail. It returns nil if any validator succeeds, otherwise returns the last validation error.

type Either

type Either []HasValidation

Either represents an exclusive OR operation for multiple validators. Exactly one validator must pass for the validation to succeed.

func (Either) Validate

func (l Either) Validate(ctx context.Context) error

Validate executes all validators and ensures exactly one passes. It returns an error if zero or more than one validator succeeds.

type HasValidation

type HasValidation interface {
	// Validate performs validation logic and returns an error if validation fails.
	// The context can be used for cancellation and timeout handling.
	Validate(ctx context.Context) error
}

HasValidation defines the interface that all validators must implement. It provides a single method for validating data with context support.

func Equal

func Equal[T comparable](value T, expected T) HasValidation

Equal validates that the value equals the expected value. It uses Go's built-in equality comparison for comparable types. It returns an error if the values don't match, otherwise returns nil.

func False

func False(value bool) HasValidation

False validates that the boolean value is false. It returns an error if the value is true, otherwise returns nil.

func LengthEqual added in v1.1.0

func LengthEqual[T any](list []T, expectedLength int) HasValidation

LengthEqual validates that the slice length equals the expected length. It returns an error if the lengths don't match, otherwise returns nil.

func LengthGe added in v1.1.0

func LengthGe[T any](list []T, expectedLength int) HasValidation

LengthGe validates that the slice length is greater than or equal to the expected length. It returns an error if the slice is shorter, otherwise returns nil.

func LengthGt added in v1.1.0

func LengthGt[T any](list []T, expectedLength int) HasValidation

LengthGt validates that the slice length is greater than the expected length. It returns an error if the slice is not longer, otherwise returns nil.

func LengthLe added in v1.1.0

func LengthLe[T any](list []T, expectedLength int) HasValidation

LengthLe validates that the slice length is less than or equal to the expected length. It returns an error if the slice is longer, otherwise returns nil.

func LengthLt added in v1.1.0

func LengthLt[T any](list []T, expectedLength int) HasValidation

LengthLt validates that the slice length is less than the expected length. It returns an error if the slice is not shorter, otherwise returns nil.

func Name

func Name(fieldname string, validation HasValidation) HasValidation

Name wraps a validator with a field name for better error messages. It executes the wrapped validator and includes the field name in any error. This is useful for providing context about which field failed validation.

func Nil

func Nil(value any) HasValidation

Nil validates that the given value is nil. It handles both nil interfaces and nil pointers correctly. It returns an error if the value is not nil, otherwise returns nil.

func NilOrValid

func NilOrValid(validation HasValidation) HasValidation

NilOrValid validates that the value is either nil or passes the provided validation. It succeeds if the validator itself is nil OR if the validator passes its validation. This is useful for optional fields that should be validated only when present.

func Not

func Not(hasValidation HasValidation) HasValidation

Not inverts the result of a validator. It returns nil if the wrapped validator fails, and an error if it succeeds. Non-validation errors are passed through unchanged.

func NotEmptySlice added in v1.2.0

func NotEmptySlice[T any](values []T) HasValidation

NotEmptySlice validates that the slice is not empty. It accepts slices of any type and checks that the length is greater than zero. It returns an error if the slice is empty, otherwise returns nil.

func NotEmptyString added in v1.2.0

func NotEmptyString[T ~string](value T) HasValidation

NotEmptyString validates that the string value is not empty. It accepts any type that has string as its underlying type. It returns an error if the string is empty, otherwise returns nil.

func NotNil

func NotNil(value any) HasValidation

NotNil validates that the given value is not nil. It returns an error if the value is nil, otherwise returns nil.

func NotNilAndValid

func NotNilAndValid(value HasValidation) HasValidation

NotNilAndValid validates that the value is not nil AND passes the provided validation. It ensures the validator is not nil before executing the validation logic. This is useful for required fields that must be present and valid.

func True

func True(value bool) HasValidation

True validates that the boolean value is true. It returns an error if the value is false, otherwise returns nil.

type HasValidationFunc

type HasValidationFunc func(ctx context.Context) error

HasValidationFunc is a function type that implements the HasValidation interface. It allows functions to be used as validators without creating custom types.

func (HasValidationFunc) Validate

func (v HasValidationFunc) Validate(ctx context.Context) error

Validate implements the HasValidation interface by calling the function itself.

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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