validation

package
v1.0.0-rc07 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Validation package

internal/core/validation provides a thread-safe registry and engine for validators. A validator has a unique name, a priority, and a Validate(context.Context, interface{}) (*ValidationResult, error) method. Results contain errors, warnings, informational issues, and suggestions.

Engine behavior

engine := validation.NewValidationEngine()
engine.MustRegister(validation.NewValidatorFunc("cluster-name", validate))
result, err := engine.Validate(ctx, "cluster-name", value)
  • Validate runs one registered validator.
  • ValidateAll runs requested validators sequentially.
  • ValidateParallel runs requested validators concurrently.
  • ValidateWithOptions and the ...WithOptions variants support StopOnFirstError and warning filtering.
  • Security validators registered with RegisterSecurityValidator run before requested validators and cannot be skipped.
  • Results are enhanced by the suggestion engine and cached by validator name plus a JSON/SHA-256 data hash. New engines use a five-minute cache; NewValidationEngineWithCache(0) disables it.

Requested validators are ordered by ascending priority for sequential and parallel execution. Standard values are PriorityHigh (50), PriorityNormal (100), and PriorityLow (200).

Implementation and tests are colocated in engine.go, registry.go, types.go, suggestions.go, cache.go, and their test files. The validators/ subpackage contains built-in validators.

Documentation

Overview

Package validation provides a unified validation engine for all validation operations.

The validation package consolidates validation logic scattered across 15+ packages into a single ValidationEngine. This eliminates duplicate code, provides consistent error messages with actionable suggestions, and establishes a single source of truth for all validation rules.

Core Components

ValidationEngine: Central registry and executor for all validators

  • Thread-safe validator registration and lookup
  • Single validator execution via Validate()
  • All validators execution via ValidateAll()
  • Result aggregation from multiple validators

Validator Interface: All validators implement this interface

  • Name() returns unique validator identifier
  • Validate() performs validation and returns results
  • Description() provides human-readable description

ValidationResult: Rich result structure with errors, warnings, and suggestions

  • Valid boolean indicating overall success
  • Errors slice containing all validation failures
  • Warnings slice for non-fatal issues
  • Suggestions slice with actionable recommendations

Usage Example

// Create validation engine
errorHandler := errors.NewDefaultErrorHandlerWithoutMasking()
engine := validation.NewValidationEngine(errorHandler)

// Register validators
engine.Register(validators.NewClusterNameValidator(errorHandler))
engine.Register(validators.NewNetworkValidator(errorHandler))

// Validate specific domain
result, err := engine.Validate(ctx, "cluster-name", "my-cluster")
if err != nil {
    log.Fatalf("validation error: %v", err)
}

if !result.Valid {
    for _, validationErr := range result.Errors {
        fmt.Printf("Error: %s\n", validationErr.Message)
        for _, suggestion := range validationErr.Suggestions {
            fmt.Printf("  - %s\n", suggestion)
        }
    }
}

// Validate all domains
result, err = engine.ValidateAll(ctx, config)
if err != nil {
    log.Fatalf("validation error: %v", err)
}

Performance

The ValidationEngine is designed for high performance:

  • <1ms overhead per individual validation operation
  • <10ms for full validation (all validators)
  • Thread-safe concurrent validation operations
  • Efficient O(1) validator lookup using maps

Security

Security validators always run and cannot be bypassed:

  • Path traversal detection
  • Command injection detection
  • Input sanitization
  • Security violations are logged for audit trail
Example (BasicValidation)

Example_basicValidation demonstrates basic validation usage.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	// Create a simple validator
	validator := validation.NewValidatorFunc("length", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, ok := value.(string)
		if !ok {
			result.AddError("value", "expected string")
			return result, nil
		}
		if len(str) < 3 {
			result.AddError("value", "must be at least 3 characters")
			return result, nil
		}
		return result, nil
	})

	// Create validation engine and register validator
	engine := validation.NewValidationEngine()
	engine.Register(validator)

	// Validate a value
	ctx := context.Background()
	result, err := engine.Validate(ctx, "length", "hello")
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if result.Valid {
		fmt.Println("Validation passed")
	} else {
		for _, e := range result.Errors {
			fmt.Printf("Error: %s\n", e.Message)
		}
	}

}
Output:
Validation passed
Example (ContextCancellation)

Example_contextCancellation demonstrates using context for cancellation.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	// Create a validator that checks context
	validator := validation.NewValidatorFunc("slow", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		default:
			return &validation.ValidationResult{Valid: true}, nil
		}
	})

	engine := validation.NewValidationEngine()
	engine.Register(validator)

	// Create context with cancellation
	ctx, cancel := context.WithCancel(context.Background())
	cancel() // Cancel immediately

	// Validation respects context cancellation
	result, err := engine.Validate(ctx, "slow", "value")

	if err != nil {
		fmt.Println("Validation cancelled")
	} else if result.Valid {
		fmt.Println("Validation passed")
	}

}
Output:
Validation cancelled
Example (CustomValidator)

Example_customValidator demonstrates creating a custom validator.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

// EmailValidator is a custom validator for email addresses.
type EmailValidator struct{}

func (v *EmailValidator) Name() string {
	return "email"
}

func (v *EmailValidator) Priority() int {
	return validation.PriorityHigh
}

func (v *EmailValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
	result := &validation.ValidationResult{Valid: true}

	email, ok := value.(string)
	if !ok {
		result.AddError("email", "value must be a string")
		return result, nil
	}

	if len(email) == 0 || !strings.Contains(email, "@") {
		result.AddError("email", "invalid email format", "email must contain @ symbol")
		return result, nil
	}

	return result, nil
}

func main() {
	// Use custom validator
	engine := validation.NewValidationEngine()
	engine.Register(&EmailValidator{})

	ctx := context.Background()
	result, _ := engine.Validate(ctx, "email", "user@example.com")

	fmt.Printf("Email valid: %v\n", result.Valid)

}
Output:
Email valid: true
Example (ErrorHandling)

Example_errorHandling demonstrates comprehensive error handling.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	engine := validation.NewValidationEngine()

	// Register a validator
	validator := validation.NewValidatorFunc("test", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)
		if strings.ToUpper(str) == str {
			result.AddError("value", "uppercase not allowed")
			result.Errors[0].Code = "INVALID_FORMAT"
		}
		return result, nil
	})
	engine.Register(validator)

	ctx := context.Background()

	// Try to use unregistered validator
	_, err := engine.Validate(ctx, "nonexistent", "value")
	if err != nil {
		fmt.Println("Error: validator not found")
	}

	// Validate with invalid input
	result, _ := engine.Validate(ctx, "test", "INVALID")
	if !result.Valid {
		fmt.Printf("Validation failed: %d errors\n", len(result.Errors))
		for _, e := range result.Errors {
			fmt.Printf("  - %s (code: %s)\n", e.Message, e.Code)
		}
	}

}
Output:
Error: validator not found
Validation failed: 1 errors
  - uppercase not allowed (code: INVALID_FORMAT)
Example (MultipleErrors)

Example_multipleErrors demonstrates collecting multiple validation errors.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	// Create validator that checks multiple conditions
	validator := validation.NewValidatorFunc("multi", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)

		if len(str) < 3 {
			result.AddError("value", "too short")
		}
		if len(str) > 10 {
			result.AddError("value", "too long")
		}
		if strings.Contains(str, " ") {
			result.AddError("value", "spaces not allowed")
		}

		return result, nil
	})

	engine := validation.NewValidationEngine()
	engine.Register(validator)

	ctx := context.Background()
	result, _ := engine.Validate(ctx, "multi", "a ")

	if !result.Valid {
		fmt.Printf("Found %d errors:\n", len(result.Errors))
		for _, e := range result.Errors {
			fmt.Printf("  - %s\n", e.Message)
		}
	}

}
Output:
Found 2 errors:
  - too short
  - spaces not allowed
Example (MultipleValidators)

Example_multipleValidators demonstrates using multiple validators.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	engine := validation.NewValidationEngine()

	// Register length validator
	lengthValidator := validation.NewValidatorFunc("length", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)
		if len(str) < 3 {
			result.AddError("value", "too short")
		}
		return result, nil
	})

	// Register format validator
	formatValidator := validation.NewValidatorFunc("format", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)
		if strings.Contains(str, " ") {
			result.AddError("value", "spaces not allowed")
		}
		return result, nil
	})

	engine.Register(lengthValidator)
	engine.Register(formatValidator)

	ctx := context.Background()

	// Validate with length validator
	result1, _ := engine.Validate(ctx, "length", "hello")
	fmt.Printf("Length valid: %v\n", result1.Valid)

	// Validate with format validator
	result2, _ := engine.Validate(ctx, "format", "hello")
	fmt.Printf("Format valid: %v\n", result2.Valid)

}
Output:
Length valid: true
Format valid: true
Example (ValidateAll)

Example_validateAll demonstrates validating with multiple validators at once.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	engine := validation.NewValidationEngine()

	// Register validators
	engine.Register(validation.NewValidatorFunc("length", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)
		if len(str) < 3 {
			result.AddError("value", "too short")
		}
		return result, nil
	}))

	engine.Register(validation.NewValidatorFunc("format", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)
		if strings.Contains(str, " ") {
			result.AddError("value", "spaces not allowed")
		}
		return result, nil
	}))

	ctx := context.Background()

	// Validate with all validators
	result, err := engine.ValidateAll(ctx, []string{"length", "format"}, "hello")
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if result.Valid {
		fmt.Println("All validations passed")
	} else {
		fmt.Printf("Validation failed with %d errors\n", len(result.Errors))
	}

}
Output:
All validations passed
Example (ValidationWithSuggestions)

Example_validationWithSuggestions demonstrates validation with suggestions.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	// Create validator that provides suggestions
	validator := validation.NewValidatorFunc("format", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, ok := value.(string)
		if !ok {
			result.AddError("value", "expected string")
			return result, nil
		}
		if strings.Contains(str, "_") {
			result.AddError("value", "underscores not allowed", "try using hyphens instead")
			return result, nil
		}
		return result, nil
	})

	engine := validation.NewValidationEngine()
	engine.Register(validator)

	ctx := context.Background()
	result, _ := engine.Validate(ctx, "format", "my_value")

	if !result.Valid {
		for _, e := range result.Errors {
			fmt.Printf("Error: %s\n", e.Message)
			if len(e.Suggestions) > 0 {
				fmt.Printf("Suggestion: %s\n", e.Suggestions[0])
			}
		}
	}

}
Output:
Error: underscores not allowed
Suggestion: try using hyphens instead
Example (Warnings)

Example_warnings demonstrates using warnings alongside errors.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
)

func main() {
	// Create validator that generates warnings
	validator := validation.NewValidatorFunc("check", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := &validation.ValidationResult{Valid: true}
		str, _ := value.(string)

		if len(str) > 50 {
			result.AddWarning("value", "unusually long", "consider shortening")
		}
		if strings.Contains(str, "test") {
			result.AddWarning("value", "contains 'test'", "remove test data before production")
		}

		return result, nil
	})

	engine := validation.NewValidationEngine()
	engine.Register(validator)

	ctx := context.Background()
	result, _ := engine.Validate(ctx, "check", "test-value")

	fmt.Printf("Valid: %v\n", result.Valid)
	fmt.Printf("Warnings: %d\n", len(result.Warnings))
	for _, w := range result.Warnings {
		fmt.Printf("  - %s\n", w.Message)
	}

}
Output:
Valid: true
Warnings: 1
  - contains 'test'

Index

Examples

Constants

View Source
const (
	// PriorityHigh is for fast validators that should run first.
	// Examples: format checks, simple pattern matching, length validation
	PriorityHigh = 50

	// PriorityNormal is for standard validators with moderate complexity.
	// Examples: business logic validation, cross-field validation
	PriorityNormal = 100

	// PriorityLow is for slow validators that should run last.
	// Examples: network connectivity checks, file I/O, external API calls
	PriorityLow = 200
)

Priority constants for validator execution ordering.

Validators with lower priority values execute first. This allows fast, simple validators to run before slow, complex validators.

Priority ranges:

  • 0-99: High priority (fast validators like format checks)
  • 100-199: Normal priority (standard business logic validators)
  • 200-299: Low priority (slow validators like network checks, file I/O)

Variables

This section is empty.

Functions

func Clear

func Clear()

Clear removes all validators from the global registry.

func Count

func Count() int

Count returns the number of validators in the global registry.

func Has

func Has(name string) bool

Has checks if a validator is registered in the global registry.

func List

func List() []string

List returns all validator names from the global registry.

func MustRegister

func MustRegister(validator Validator)

MustRegister registers a validator with the global registry and panics on error.

func Register

func Register(validator Validator) error

Register registers a validator with the global registry.

func Unregister

func Unregister(name string) error

Unregister removes a validator from the global registry.

Types

type CacheEntry

type CacheEntry struct {
	Result    *ValidationResult
	ExpiresAt time.Time
}

CacheEntry represents a cached validation result with expiration.

func (*CacheEntry) IsExpired

func (e *CacheEntry) IsExpired() bool

IsExpired returns true if the cache entry has expired.

type CacheStats

type CacheStats struct {
	Total   int
	Expired int
}

Stats returns cache statistics.

Returns:

  • total: Total number of entries
  • expired: Number of expired entries

type ContextSuggestionRule

type ContextSuggestionRule struct{}

ContextSuggestionRule generates context-aware suggestions based on field type.

func (*ContextSuggestionRule) Generate

func (r *ContextSuggestionRule) Generate(issue *ValidationIssue, context map[string]interface{}) []string

Generate generates context-aware suggestions.

func (*ContextSuggestionRule) Name

func (r *ContextSuggestionRule) Name() string

Name returns the rule name.

type Registry

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

Registry manages validator registration and lookup.

func GlobalRegistry

func GlobalRegistry() *Registry

GlobalRegistry returns the global validator registry.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new validator registry.

func (*Registry) Clear

func (r *Registry) Clear()

Clear removes all validators from the registry.

func (*Registry) Clone

func (r *Registry) Clone() *Registry

Clone creates a copy of the registry with all registered validators.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered validators.

func (*Registry) Get

func (r *Registry) Get(name string) Validator

Get retrieves a validator by name. Returns nil if the validator is not found.

func (*Registry) Has

func (r *Registry) Has(name string) bool

Has checks if a validator is registered.

func (*Registry) List

func (r *Registry) List() []string

List returns a list of all registered validator names.

func (*Registry) MustRegister

func (r *Registry) MustRegister(validator Validator)

MustRegister registers a validator and panics if registration fails. This is useful for registering validators during initialization.

func (*Registry) Register

func (r *Registry) Register(validator Validator) error

Register registers a validator with the registry. Returns an error if a validator with the same name is already registered.

func (*Registry) Unregister

func (r *Registry) Unregister(name string) error

Unregister removes a validator from the registry. Returns an error if the validator is not found.

type Severity

type Severity string

Severity represents the severity level of a validation issue.

const (
	// SeverityError indicates a validation error that must be fixed.
	SeverityError Severity = "error"
	// SeverityWarning indicates a validation warning that should be reviewed.
	SeverityWarning Severity = "warning"
	// SeverityInfo indicates informational validation feedback.
	SeverityInfo Severity = "info"
)

type SuggestionEngine

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

SuggestionEngine generates helpful suggestions for validation errors.

Example (Complete)

ExampleSuggestionEngine_complete demonstrates the complete workflow.

// Create suggestion engine
engine := NewSuggestionEngine()

// Create a validation result with an error
result := &ValidationResult{
	Valid: false,
	Errors: []*ValidationIssue{
		{
			Severity: SeverityError,
			Field:    "cluster.provider",
			Message:  "invalid value 'openstck'",
		},
	},
}

// Enhance with suggestions
context := map[string]interface{}{
	"valid_values": []string{"openstack", "aws", "gcp"},
}

engine.EnhanceResult(result, context)

// Print the enhanced result
for _, err := range result.Errors {
	fmt.Printf("Error: %s\n", err.Message)
	fmt.Printf("Suggestions:\n")
	for _, s := range err.Suggestions {
		fmt.Printf("  - %s\n", s)
	}
}
Output:
Error: invalid value 'openstck'
Suggestions:
  - Did you mean "openstack"?
  - Use alphanumeric characters, hyphens, and underscores only

func NewSuggestionEngine

func NewSuggestionEngine() *SuggestionEngine

NewSuggestionEngine creates a new suggestion engine with default rules.

func (*SuggestionEngine) AddRule

func (e *SuggestionEngine) AddRule(rule SuggestionRule)

AddRule adds a suggestion rule to the engine.

func (*SuggestionEngine) EnhanceResult

func (e *SuggestionEngine) EnhanceResult(result *ValidationResult, context map[string]interface{})

EnhanceResult enhances a validation result with suggestions.

type SuggestionRule

type SuggestionRule interface {
	// Name returns the unique name of the rule.
	Name() string
	// Generate generates suggestions for a validation issue.
	Generate(issue *ValidationIssue, context map[string]interface{}) []string
}

SuggestionRule defines the interface for suggestion generation rules.

type TypoSuggestionRule

type TypoSuggestionRule struct{}

TypoSuggestionRule suggests corrections for typos using Levenshtein distance.

func (*TypoSuggestionRule) Generate

func (r *TypoSuggestionRule) Generate(issue *ValidationIssue, context map[string]interface{}) []string

Generate generates typo correction suggestions.

func (*TypoSuggestionRule) Name

func (r *TypoSuggestionRule) Name() string

Name returns the rule name.

type ValidationCache

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

ValidationCache provides caching for validation results.

The cache stores validation results keyed by validator name and data hash. Entries expire after a configurable TTL (default 5 minutes).

Features:

  • Thread-safe concurrent access
  • Automatic expiration of stale entries
  • Data hash-based invalidation
  • Configurable TTL per entry

Example usage:

cache := validation.NewValidationCache(5 * time.Minute)

// Try to get cached result
if result := cache.Get("cluster-name", data); result != nil {
    return result, nil
}

// Cache miss - perform validation
result := validator.Validate(ctx, data)
cache.Set("cluster-name", data, result, 5 * time.Minute)

func NewValidationCache

func NewValidationCache(ttl time.Duration) *ValidationCache

NewValidationCache creates a new validation cache with the specified TTL.

Parameters:

  • ttl: Time-to-live for cache entries (0 disables caching)

Returns:

  • *ValidationCache: New cache instance

Example:

cache := validation.NewValidationCache(5 * time.Minute)

func (*ValidationCache) CleanExpired

func (c *ValidationCache) CleanExpired() int

CleanExpired removes all expired entries from the cache.

This method should be called periodically to prevent memory leaks from expired entries. Consider running it in a background goroutine.

Returns:

  • int: Number of entries removed

Example:

// Run cleanup every minute
go func() {
    ticker := time.NewTicker(1 * time.Minute)
    defer ticker.Stop()
    for range ticker.C {
        removed := cache.CleanExpired()
        log.Printf("Cleaned %d expired cache entries", removed)
    }
}()

func (*ValidationCache) Clear

func (c *ValidationCache) Clear()

Clear removes all cached entries.

Example:

cache.Clear() // Clear all cached validation results

func (*ValidationCache) Get

func (c *ValidationCache) Get(validatorName string, data interface{}) *ValidationResult

Get retrieves a cached validation result.

Returns nil if:

  • No cached entry exists
  • The cached entry has expired
  • The data hash doesn't match (data changed)

Parameters:

  • validatorName: Name of the validator
  • data: Data to validate (used for hash calculation)

Returns:

  • *ValidationResult: Cached result or nil if not found/expired

Example:

if result := cache.Get("cluster-name", clusterName); result != nil {
    // Cache hit - use cached result
    return result, nil
}

func (*ValidationCache) Invalidate

func (c *ValidationCache) Invalidate(validatorName string, data interface{})

Invalidate removes a cached entry.

Parameters:

  • validatorName: Name of the validator
  • data: Data to invalidate

Example:

// Data changed - invalidate cache
cache.Invalidate("cluster-name", oldData)

func (*ValidationCache) InvalidateAll

func (c *ValidationCache) InvalidateAll(validatorName string)

InvalidateAll removes all cached entries for a validator.

Parameters:

  • validatorName: Name of the validator

Example:

// Validator logic changed - invalidate all entries
cache.InvalidateAll("cluster-name")

func (*ValidationCache) Set

func (c *ValidationCache) Set(validatorName string, data interface{}, result *ValidationResult, ttl time.Duration)

Set stores a validation result in the cache.

The result is stored with the specified TTL. If ttl is 0, the cache's default TTL is used.

Parameters:

  • validatorName: Name of the validator
  • data: Data that was validated
  • result: Validation result to cache
  • ttl: Time-to-live for this entry (0 uses default)

Example:

result := validator.Validate(ctx, data)
cache.Set("cluster-name", data, result, 5 * time.Minute)

func (*ValidationCache) Size

func (c *ValidationCache) Size() int

Size returns the number of cached entries.

Returns:

  • int: Number of entries in cache

func (*ValidationCache) Stats

func (c *ValidationCache) Stats() CacheStats

Stats returns cache statistics.

Returns:

  • CacheStats: Cache statistics

type ValidationEngine

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

ValidationEngine manages validator registration and execution.

The engine provides:

  • Thread-safe validator registration and lookup
  • Single validator execution via Validate()
  • Multiple validator execution via ValidateAll()
  • Parallel validation via ValidateParallel()
  • Automatic suggestion generation
  • Always-run security validators that cannot be bypassed
  • Validation result caching with automatic expiration

Example usage:

engine := validation.NewValidationEngine()
engine.Register(myValidator)
result, err := engine.Validate(ctx, "my-validator", value)

func DefaultEngine

func DefaultEngine() *ValidationEngine

DefaultEngine returns the global default validation engine.

This is useful for simple use cases where a single global engine is sufficient.

Returns:

  • *ValidationEngine: Global validation engine

func NewValidationEngine

func NewValidationEngine() *ValidationEngine

NewValidationEngine creates a new validation engine.

The engine is initialized with:

  • Empty validator registry
  • Default suggestion engine with typo detection
  • Empty security validators list
  • Validation cache with 5-minute TTL

Returns:

  • *ValidationEngine: New validation engine instance

func NewValidationEngineWithCache

func NewValidationEngineWithCache(cacheTTL time.Duration) *ValidationEngine

NewValidationEngineWithCache creates a new validation engine with custom cache TTL.

Parameters:

  • cacheTTL: Time-to-live for cache entries (0 disables caching)

Returns:

  • *ValidationEngine: New validation engine instance

Example:

// Create engine with 10-minute cache
engine := validation.NewValidationEngineWithCache(10 * time.Minute)

// Create engine with caching disabled
engine := validation.NewValidationEngineWithCache(0)

func (*ValidationEngine) AddSuggestionRule

func (e *ValidationEngine) AddSuggestionRule(rule SuggestionRule)

AddSuggestionRule adds a custom suggestion rule to the engine.

Parameters:

  • rule: Suggestion rule to add

func (*ValidationEngine) CacheStats

func (e *ValidationEngine) CacheStats() CacheStats

CacheStats returns cache statistics.

Returns:

  • CacheStats: Cache statistics

func (*ValidationEngine) CleanExpiredCache

func (e *ValidationEngine) CleanExpiredCache() int

CleanExpiredCache removes expired entries from the cache.

Returns:

  • int: Number of entries removed

Example:

removed := engine.CleanExpiredCache()
log.Printf("Cleaned %d expired cache entries", removed)

func (*ValidationEngine) ClearCache

func (e *ValidationEngine) ClearCache()

ClearCache removes all cached validation results.

Example:

engine.ClearCache() // Clear all cached results

func (*ValidationEngine) GetCache

func (e *ValidationEngine) GetCache() *ValidationCache

GetCache returns the validation cache.

Returns:

  • *ValidationCache: Validation cache

func (*ValidationEngine) GetRegistry

func (e *ValidationEngine) GetRegistry() *Registry

GetRegistry returns the validator registry.

Returns:

  • *Registry: Validator registry

func (*ValidationEngine) GetSuggestionEngine

func (e *ValidationEngine) GetSuggestionEngine() *SuggestionEngine

GetSuggestionEngine returns the suggestion engine.

Returns:

  • *SuggestionEngine: Suggestion engine

func (*ValidationEngine) Has

func (e *ValidationEngine) Has(name string) bool

Has checks if a validator is registered.

Parameters:

  • name: Validator name to check

Returns:

  • bool: True if validator exists

func (*ValidationEngine) InvalidateAllCache

func (e *ValidationEngine) InvalidateAllCache(validatorName string)

InvalidateAllCache invalidates all cached results for a validator.

Parameters:

  • validatorName: Name of the validator

Example:

// Validator logic changed - invalidate all entries
engine.InvalidateAllCache("cluster-name")

func (*ValidationEngine) InvalidateCache

func (e *ValidationEngine) InvalidateCache(validatorName string, data interface{})

InvalidateCache invalidates cached results for a specific validator and data.

Parameters:

  • validatorName: Name of the validator
  • data: Data to invalidate

Example:

// Data changed - invalidate cache
engine.InvalidateCache("cluster-name", oldData)

func (*ValidationEngine) List

func (e *ValidationEngine) List() []string

List returns names of all registered validators.

Returns:

  • []string: Validator names (empty if none registered)

func (*ValidationEngine) ListSecurityValidators

func (e *ValidationEngine) ListSecurityValidators() []string

ListSecurityValidators returns names of all registered security validators.

Returns:

  • []string: Security validator names (empty if none registered)

func (*ValidationEngine) MustRegister

func (e *ValidationEngine) MustRegister(validator Validator)

MustRegister registers a validator and panics on error.

This is useful for registering validators during initialization where registration failure should be fatal.

Parameters:

  • validator: Validator to register

Panics:

  • If registration fails

Example:

engine.MustRegister(myValidator) // Panics if registration fails

func (*ValidationEngine) MustRegisterSecurityValidator

func (e *ValidationEngine) MustRegisterSecurityValidator(validator Validator)

MustRegisterSecurityValidator registers a security validator and panics on error.

Parameters:

  • validator: Security validator to register

Panics:

  • If registration fails

func (*ValidationEngine) Register

func (e *ValidationEngine) Register(validator Validator) error

Register registers a validator with the engine.

The validator name must be unique. Attempting to register a validator with a duplicate name returns an error.

Parameters:

  • validator: Validator to register (must not be nil)

Returns:

  • error: Registration error (nil on success)

Example:

validator := validation.NewValidatorFunc("cluster-name", validateClusterName)
err := engine.Register(validator)

func (*ValidationEngine) RegisterSecurityValidator

func (e *ValidationEngine) RegisterSecurityValidator(validator Validator) error

RegisterSecurityValidator registers a security validator that always runs.

Security validators are executed automatically in all validation operations and cannot be bypassed. This ensures security checks are always applied.

Parameters:

  • validator: Security validator to register

Returns:

  • error: Registration error (nil on success)

Example:

secValidator := validators.NewSecurityValidator()
err := engine.RegisterSecurityValidator(secValidator)

func (*ValidationEngine) Unregister

func (e *ValidationEngine) Unregister(name string) error

Unregister removes a validator from the engine.

Parameters:

  • name: Validator name to remove

Returns:

  • error: Error if validator not found

func (*ValidationEngine) Validate

func (e *ValidationEngine) Validate(ctx context.Context, name string, value interface{}) (*ValidationResult, error)

Validate executes a specific validator.

The validator must be registered before calling this method. The context can be used for cancellation and passing metadata.

Security validators are automatically executed before the requested validator to ensure security checks cannot be bypassed.

Caching: Results are cached based on validator name and data hash. Cached results are returned if available and not expired, avoiding redundant validation.

Parameters:

  • ctx: Context for cancellation and metadata
  • name: Validator name to execute
  • value: Value to validate

Returns:

  • *ValidationResult: Validation result with errors/warnings
  • error: Execution error (not validation failure)

Example:

result, err := engine.Validate(ctx, "cluster-name", "my-cluster")
if err != nil {
    return err // Execution error
}
if !result.Valid {
    // Handle validation errors
}

func (*ValidationEngine) ValidateAll

func (e *ValidationEngine) ValidateAll(ctx context.Context, names []string, value interface{}) (*ValidationResult, error)

ValidateAll executes multiple validators sequentially.

All validators are executed even if some fail. The results are aggregated into a single ValidationResult.

Parameters:

  • ctx: Context for cancellation and metadata
  • names: Validator names to execute
  • value: Value to validate

Returns:

  • *ValidationResult: Aggregated validation result
  • error: Execution error (not validation failure)

Example:

result, err := engine.ValidateAll(ctx, []string{"validator1", "validator2"}, value)

func (*ValidationEngine) ValidateAllWithOptions

func (e *ValidationEngine) ValidateAllWithOptions(ctx context.Context, names []string, value interface{}, opts *ValidationOptions) (*ValidationResult, error)

ValidateAllWithOptions executes multiple validators with custom options.

Security validators are automatically executed first to ensure security checks cannot be bypassed.

Validators are sorted by priority before execution, with lower priority values running first. This ensures fast validators (format checks) run before slow validators (network checks, file I/O).

Parameters:

  • ctx: Context for cancellation and metadata
  • names: Validator names to execute
  • value: Value to validate
  • opts: Validation options (nil for defaults)

Returns:

  • *ValidationResult: Aggregated validation result
  • error: Execution error

func (*ValidationEngine) ValidateParallel

func (e *ValidationEngine) ValidateParallel(ctx context.Context, names []string, value interface{}) (*ValidationResult, error)

ValidateParallel executes multiple validators in parallel.

All validators run concurrently using goroutines. This is faster than ValidateAll for independent validators but uses more resources.

Parameters:

  • ctx: Context for cancellation and metadata
  • names: Validator names to execute
  • value: Value to validate

Returns:

  • *ValidationResult: Aggregated validation result
  • error: Execution error (not validation failure)

Example:

result, err := engine.ValidateParallel(ctx, []string{"validator1", "validator2"}, value)

func (*ValidationEngine) ValidateParallelWithOptions

func (e *ValidationEngine) ValidateParallelWithOptions(ctx context.Context, names []string, value interface{}, opts *ValidationOptions) (*ValidationResult, error)

ValidateParallelWithOptions executes multiple validators in parallel with options.

Security validators are executed first sequentially to ensure security checks cannot be bypassed, then the requested validators run in parallel.

Note: Validators are sorted by priority before parallel execution. While they run concurrently, validators with the same priority level are grouped together.

Parameters:

  • ctx: Context for cancellation and metadata
  • names: Validator names to execute
  • value: Value to validate
  • opts: Validation options (nil for defaults)

Returns:

  • *ValidationResult: Aggregated validation result
  • error: Execution error

func (*ValidationEngine) ValidateWithOptions

func (e *ValidationEngine) ValidateWithOptions(ctx context.Context, name string, value interface{}, opts *ValidationOptions) (*ValidationResult, error)

ValidateWithOptions executes a validator with custom options.

Parameters:

  • ctx: Context for cancellation and metadata
  • name: Validator name to execute
  • value: Value to validate
  • opts: Validation options (nil for defaults)

Returns:

  • *ValidationResult: Validation result
  • error: Execution error

type ValidationIssue

type ValidationIssue struct {
	// Severity indicates the severity level of the issue.
	Severity Severity
	// Field is the field path that failed validation (e.g., "cluster.name").
	Field string
	// Message is a human-readable description of the issue.
	Message string
	// Code is an optional error code for programmatic handling.
	Code string
	// Suggestions contains helpful suggestions for fixing the issue.
	Suggestions []string
	// Context contains additional context about the validation failure.
	Context map[string]interface{}
}

ValidationIssue represents a single validation issue.

Each issue contains:

  • Severity: Error, warning, or info
  • Field: Path to the field that failed (e.g., "cluster.name")
  • Message: Human-readable description
  • Code: Optional error code for programmatic handling
  • Suggestions: Helpful suggestions for fixing the issue
  • Context: Additional metadata about the failure

Example:

issue := &validation.ValidationIssue{
    Severity: validation.SeverityError,
    Field: "cluster.name",
    Message: "name must be lowercase",
    Code: "INVALID_NAME_FORMAT",
    Suggestions: []string{
        "Use lowercase letters only",
        "Example: my-cluster",
    },
}

func (*ValidationIssue) Error

func (v *ValidationIssue) Error() string

Error implements the error interface for ValidationIssue.

type ValidationOptions

type ValidationOptions struct {
	// StopOnFirstError stops validation after the first error.
	StopOnFirstError bool
	// IncludeWarnings includes warnings in the validation result.
	IncludeWarnings bool
	// Context contains additional context for validation.
	Context map[string]interface{}
}

ValidationOptions contains options for validation operations.

func DefaultValidationOptions

func DefaultValidationOptions() *ValidationOptions

DefaultValidationOptions returns the default validation options.

type ValidationResult

type ValidationResult struct {
	// Valid indicates whether the validation passed.
	Valid bool
	// Errors contains all validation errors.
	Errors []*ValidationIssue
	// Warnings contains all validation warnings.
	Warnings []*ValidationIssue
	// Info contains informational messages.
	Info []*ValidationIssue
}

ValidationResult represents the result of a validation operation.

A validation result contains:

  • Valid: Overall validation status (false if any errors)
  • Errors: Critical issues that must be fixed
  • Warnings: Issues that should be reviewed but don't block
  • Info: Informational messages

Example usage:

result := validation.NewValidationResult()
result.AddError("cluster.name", "name is required")
result.AddWarning("cluster.region", "region not specified, using default")

if !result.Valid {
    for _, err := range result.Errors {
        fmt.Printf("Error: %s\n", err.Message)
        for _, suggestion := range err.Suggestions {
            fmt.Printf("  Suggestion: %s\n", suggestion)
        }
    }
}

func NewValidationResult

func NewValidationResult() *ValidationResult

NewValidationResult creates a new ValidationResult with pre-allocated slices.

Pre-allocates capacity for 4 errors, 4 warnings, and 4 info messages to reduce allocations during validation. The result is marked as valid by default.

Example:

result := validation.NewValidationResult()
result.AddError("field", "error message")
return result

func Validate

func Validate(ctx context.Context, name string, value interface{}) (*ValidationResult, error)

Validate validates a value using the default engine.

This is a convenience function for simple validation without creating an engine.

Parameters:

  • ctx: Context for cancellation and metadata
  • name: Validator name to execute
  • value: Value to validate

Returns:

  • *ValidationResult: Validation result
  • error: Execution error

func ValidateAll

func ValidateAll(ctx context.Context, names []string, value interface{}) (*ValidationResult, error)

ValidateAll validates a value using multiple validators from the default engine.

Parameters:

  • ctx: Context for cancellation and metadata
  • names: Validator names to execute
  • value: Value to validate

Returns:

  • *ValidationResult: Aggregated validation result
  • error: Execution error

func ValidateParallel

func ValidateParallel(ctx context.Context, names []string, value interface{}) (*ValidationResult, error)

ValidateParallel validates a value using multiple validators in parallel from the default engine.

Parameters:

  • ctx: Context for cancellation and metadata
  • names: Validator names to execute
  • value: Value to validate

Returns:

  • *ValidationResult: Aggregated validation result
  • error: Execution error

func (*ValidationResult) AddError

func (r *ValidationResult) AddError(field, message string, suggestions ...string)

AddError adds an error to the validation result.

Errors indicate critical issues that must be fixed before proceeding. Adding an error sets Valid to false.

Parameters:

  • field: Field path (e.g., "cluster.name")
  • message: Human-readable error description
  • suggestions: Optional suggestions for fixing the error

Example:

result.AddError("cluster.name", "name is required")
result.AddError("cluster.region", "invalid region", "Use us-east-1 or us-west-2")

func (*ValidationResult) AddInfo

func (r *ValidationResult) AddInfo(field, message string)

AddInfo adds an informational message to the validation result.

func (*ValidationResult) AddWarning

func (r *ValidationResult) AddWarning(field, message string, suggestions ...string)

AddWarning adds a warning to the validation result.

func (*ValidationResult) HasErrors

func (r *ValidationResult) HasErrors() bool

HasErrors returns true if the result contains any errors.

func (*ValidationResult) HasIssues

func (r *ValidationResult) HasIssues() bool

HasIssues returns true if the result contains any errors or warnings.

func (*ValidationResult) HasWarnings

func (r *ValidationResult) HasWarnings() bool

HasWarnings returns true if the result contains any warnings.

func (*ValidationResult) Merge

func (r *ValidationResult) Merge(other *ValidationResult)

Merge merges another ValidationResult into this one.

This method combines errors, warnings, and info messages from another result. If the other result is invalid, this result becomes invalid.

Pre-allocates capacity to avoid multiple reallocations when merging large results.

Parameters:

  • other: ValidationResult to merge (nil-safe)

Example:

result1 := validator1.Validate(ctx, value)
result2 := validator2.Validate(ctx, value)
result1.Merge(result2) // Combine results

func (*ValidationResult) ToError

func (r *ValidationResult) ToError() error

ToError converts ValidationResult to a StructuredError.

This method provides compatibility with the error handling system by converting validation results into structured errors that can be handled uniformly.

Behavior:

  • Returns nil if Valid is true (no errors)
  • Returns nil if there are no errors (even if Valid is false)
  • Returns a single StructuredError if there's one error
  • Returns a StructuredError with aggregated messages if there are multiple errors

The returned StructuredError includes:

  • Type: ValidationError
  • Message: Aggregated error messages (semicolon-separated)
  • Suggestions: All suggestions from all errors
  • Field: Field from first error (if only one error)
  • Context: Combined context from all errors
  • Retryable: false (validation errors require user action)

Example:

result := validator.Validate(ctx, value)
if err := result.ToError(); err != nil {
    return fmt.Errorf("validation failed: %w", err)
}

Returns:

  • error: StructuredError if validation failed, nil otherwise

type Validator

type Validator interface {
	// Name returns the unique name of the validator.
	//
	// The name must be unique within a ValidationEngine and is used to
	// identify the validator when calling Validate() or ValidateAll().
	//
	// Convention: Use lowercase with hyphens (e.g., "cluster-name", "config-syntax")
	//
	// Returns:
	//   - string: Unique validator name
	Name() string

	// Priority returns the execution priority of the validator.
	//
	// Validators with lower priority values execute first. This allows fast,
	// simple validators (like format checks) to run before slow, complex
	// validators (like network checks or file I/O).
	//
	// Standard priority levels:
	//   - PriorityHigh (0-99): Fast validators (format checks, simple rules)
	//   - PriorityNormal (100-199): Standard validators (business logic)
	//   - PriorityLow (200-299): Slow validators (network, file I/O)
	//
	// Returns:
	//   - int: Priority value (lower values execute first)
	Priority() int

	// Validate performs validation on the given value.
	// The context can be used for cancellation and passing metadata.
	//
	// Implementations should:
	//   - Be thread-safe (can be called concurrently)
	//   - Respect context cancellation
	//   - Return ValidationResult with errors, warnings, and suggestions
	//   - Not panic (return errors instead)
	//
	// Parameters:
	//   - ctx: Context for cancellation and metadata
	//   - value: Value to validate (type depends on validator)
	//
	// Returns:
	//   - *ValidationResult: Validation result with errors/warnings
	//   - error: Execution error (not validation failure)
	Validate(ctx context.Context, value interface{}) (*ValidationResult, error)
}

Validator defines the interface for all validators.

Validators must:

  • Have a unique name (returned by Name())
  • Implement Validate() to perform validation logic
  • Be thread-safe (can be called concurrently)
  • Return ValidationResult with errors, warnings, and suggestions
  • Define a priority for execution ordering (lower values run first)

Example implementation:

type MyValidator struct{}

func (v *MyValidator) Name() string {
    return "my-validator"
}

func (v *MyValidator) Priority() int {
    return PriorityNormal
}

func (v *MyValidator) Validate(ctx context.Context, value interface{}) (*ValidationResult, error) {
    result := validation.NewValidationResult()
    // Perform validation...
    if invalid {
        result.AddError("field", "error message", "suggestion")
    }
    return result, nil
}

func Get

func Get(name string) Validator

Get retrieves a validator from the global registry.

type ValidatorFunc

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

ValidatorFunc is a function type that implements the Validator interface.

func NewValidatorFunc

func NewValidatorFunc(name string, fn func(ctx context.Context, value interface{}) (*ValidationResult, error)) *ValidatorFunc

NewValidatorFunc creates a new ValidatorFunc with normal priority.

func NewValidatorFuncWithPriority

func NewValidatorFuncWithPriority(name string, priority int, fn func(ctx context.Context, value interface{}) (*ValidationResult, error)) *ValidatorFunc

NewValidatorFuncWithPriority creates a new ValidatorFunc with custom priority.

func (*ValidatorFunc) Name

func (v *ValidatorFunc) Name() string

Name returns the validator name.

func (*ValidatorFunc) Priority

func (v *ValidatorFunc) Priority() int

Priority returns the validator priority.

func (*ValidatorFunc) Validate

func (v *ValidatorFunc) Validate(ctx context.Context, value interface{}) (*ValidationResult, error)

Validate executes the validation function.

Directories

Path Synopsis
Package validators provides built-in validators for common validation tasks.
Package validators provides built-in validators for common validation tasks.

Jump to

Keyboard shortcuts

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