engine

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2025 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package engine provides validation rule types and logic for data validation. It defines various rule types that can be used to validate different aspects of data such as equality, comparison, emptiness, pattern matching, and length.

Package engine provides a flexible and extensible validation engine for Go structs. It allows defining validation rules for struct fields and validating them against various constraints. The package is designed to be simple to use while providing powerful validation capabilities.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidType      = errors.New("invalid struct or type")
	ErrFieldNotFound    = errors.New("field not found")
	ErrValidationFailed = errors.New("validation failed")
	ErrInvalidValue     = errors.New("invalid value")
	ErrInvalidArgument  = errors.New("invalid argument")
	ErrInvalidState     = errors.New("invalid state")
	ErrInvalidOperation = errors.New("invalid operation")
)

Errors represents the errors that can occur during validation. It contains information about the type of error, the field that failed validation, the rule that caused the error, and an exception that may provide additional context.

Functions

This section is empty.

Types

type CustomValidatorFunc

type CustomValidatorFunc func(value interface{}) (bool, string)

CustomValidatorFunc is a function type that can be used to implement custom validation logic. It takes a value and returns a boolean indicating whether the value is valid, and a string describing the error if the value is invalid.

type PatialValidationRule

type PatialValidationRule struct {
	Rule     RuleType
	Expected interface{} // Expected value for the rule (can be string, int, regex, etc.)
	Message  string
}

PatialValidationRule represents a partial validation rule that can be applied to a field. It contains the type of rule to be applied and the expected value for the rule.

type RuleType

type RuleType string

RuleType represents the type of validation rule to be applied. Each rule type corresponds to a specific validation operation that can be performed on data fields.

const (
	// ShouldEqual validates that a field equals a specific value.
	// Example: field should equal "expected_value"
	ShouldEqual RuleType = "Equal"

	// ShouldNotEqual validates that a field does not equal a specific value.
	// Example: field should not equal "forbidden_value"
	ShouldNotEqual RuleType = "NotEqual"

	// ShouldGreaterThan validates that a field is greater than a specific value.
	// Example: field should be greater than 10
	ShouldGreaterThan RuleType = "GreaterThan"

	// ShouldGreaterOrEqualThan validates that a field is greater than or equal to a specific value.
	// Example: field should be greater than or equal to 5
	ShouldGreaterOrEqualThan RuleType = "GreaterOrEqualThan"

	// ShouldLessThan validates that a field is less than a specific value.
	// Example: field should be less than 100
	ShouldLessThan RuleType = "LessThan"

	// ShouldLessOrEqualThan validates that a field is less than or equal to a specific value.
	// Example: field should be less than or equal to 50
	ShouldLessOrEqualThan RuleType = "LessOrEqualThan"

	// ShouldEmpty validates that a field is empty (null, empty string, empty array, etc.).
	// Example: field should be empty
	ShouldEmpty RuleType = "Empty"

	// ShouldNotEmpty validates that a field is not empty.
	// Example: field should not be empty
	ShouldNotEmpty RuleType = "NotEmpty"

	// ShouldMatch validates that a field matches a specific pattern (regex).
	// Example: field should match regex pattern "^[a-zA-Z]+$"
	ShouldMatch RuleType = "Match"

	// ShouldNotMatch validates that a field does not match a specific pattern (regex).
	// Example: field should not match regex pattern "\\d+"
	ShouldNotMatch RuleType = "NotMatch"

	// ShouldLength validates that a field has a specific length.
	// Example: field should have length 10
	ShouldLength RuleType = "Length"

	// ShouldMinLength validates that a field has a minimum length.
	// Example: field should have minimum length 5
	ShouldMinLength RuleType = "MinLength"

	// Must validates that a field must satisfy a custom validation function.
	// This is a generic rule type that allows for custom validation logic.
	// Example: field must pass custom validation function
	Must RuleType = "Must"
)

type ValidationError

type ValidationError struct {
	Field            string
	Rule             RuleType
	Message          string
	Exception        error
	ExceptionMessage string
}

ValidationError represents an error that occurs during validation. It contains information about the field that failed validation, the rule that caused the error, a message describing the error, and an exception that may provide additional context.

type ValidationResult

type ValidationResult struct {
	Errors []ValidationError
}

ValidationResult holds the results of a validation operation. It contains a slice of ValidationError that describes all validation failures.

type ValidationRule

type ValidationRule struct {
	FieldName string
	Rule      RuleType
	Expected  interface{} // Expected value for the rule (can be string, int, regex, etc.)
	Message   *string
}

ValidationRule represents a validation rule that can be applied to a field. It contains the name of the field, the type of rule to be applied, the expected value for the rule, and an optional message to be displayed when the rule fails.

func (ValidationRule) Validate

func (r ValidationRule) Validate(value interface{}) *ValidationError

Validate checks if the given value satisfies the validation rule. It returns a ValidationError if the value does not satisfy the rule, or nil if the value satisfies the rule.

The function uses reflection to determine the type of the value and the expected value, and then performs the appropriate validation based on the rule type.

The function returns a ValidationError if the value does not satisfy the rule,

type ValidatorEngine

type ValidatorEngine struct {
	Rules []ValidationRule
}

ValidatorEngine is the core validation engine that manages validation rules and performs validation of structs against those rules.

func NewValidator

func NewValidator() *ValidatorEngine

NewValidator creates and returns a new instance of ValidatorEngine. The returned validator has no rules initially; rules must be added using AddRule or AddRules methods.

func (*ValidatorEngine) AddRule

func (v *ValidatorEngine) AddRule(fieldName string, rule RuleType, expected interface{}, message string)

AddRule adds a single validation rule for a specific field. Parameters:

  • fieldName: The name of the struct field to validate
  • rule: The type of validation to perform (e.g., Required, Min, Max, etc.)
  • expected: The expected value for the validation rule (e.g., min length, max value)
  • message: Custom error message to use if validation fails

Example:

validator.AddRule("Username", Required, nil, "username is required")
validator.AddRule("Age", Min, 18, "age must be at least 18")

func (*ValidatorEngine) AddRules

func (v *ValidatorEngine) AddRules(fieldName string, rules []PatialValidationRule)

AddRules adds multiple validation rules for a single field. This is a convenience method for adding several rules to the same field at once. Parameters:

  • fieldName: The name of the struct field to validate
  • rules: A slice of PatialValidationRule containing the validation rules

func (*ValidatorEngine) Validate

func (v *ValidatorEngine) Validate(data interface{}) ValidationResult

Validate performs validation on the provided struct value according to the defined rules. It returns a ValidationResult containing any validation errors. Parameters:

  • data: The struct to validate (can be a pointer to a struct)

Returns:

  • ValidationResult containing any validation errors that occurred

The method will return an error if the input is not a struct or pointer to a struct.

Jump to

Keyboard shortcuts

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