Documentation
¶
Overview ¶
Package vix provides a type-safe, expressive, and extensible validation library for Go. It follows clean architecture principles and integrates seamlessly with the ERM centralized error management package for unified error handling and error collection with custom lightweight i18n support.
Unlike tag-based validation libraries, this package uses function chaining to create readable and maintainable validation rules. The package supports type-safe validation with Go generics, internationalization using the custom i18n package through ERM integration, conditional validation, and comprehensive error reporting suitable for modern APIs.
All validation errors are now unified under the erm.Error interface, providing consistent error handling across application and validation layers with on-demand localization support.
Message Constants Architecture ¶
VIX uses centralized message constants defined in the ERM package (erm.Msg* constants) to ensure type safety and avoid hardcoded strings. All validation messages are managed by ERM's localization system, providing consistent internationalization across the entire validation framework.
Example usage:
err := vix.String("", "email").Required().Validate()
// Uses erm.MsgRequired internally for localized error messages
Quick Start ¶
Basic validation example:
import "github.com/c3p0-box/utils/vix"
// Single field validation
err := vix.String("john@example.com", "email").
Required().
Email().
MaxLength(100).
Validate()
if err != nil {
log.Printf("Email validation failed: %v", err)
}
Multi-Field Validation ¶
The package excels at validating multiple fields with structured error output:
val := vix.Is(
vix.String("", "email").Required().Email(),
vix.Int(16, "age").Required().Min(18),
)
if !val.Valid() {
errorMap := val.ErrMap()
jsonBytes, _ := val.ToJSON()
// Returns structured error map suitable for API responses
}
Conditional Validation ¶
Validators support conditional logic:
err := vix.String(phone, "phone").
When(func() bool { return email == "" }).
Required().
Validate()
Integration with Clean Architecture ¶
The package integrates seamlessly with onion/clean architecture patterns using the unified erm error management system:
func (s *UserService) CreateUser(user User) error {
if err := vix.String(user.Email, "email").Required().Email().Validate(); err != nil {
return erm.BadRequest("Invalid email", err)
}
// Business logic continues...
return nil
}
Internationalization ¶
Error messages are localized using the custom i18n package (github.com/c3p0-box/utils/i18n) through ERM integration. Set up a localizer in your application initialization:
// Get localizers for different languages englishLocalizer := erm.GetLocalizer(language.English) spanishLocalizer := erm.GetLocalizer(language.Spanish)
All validation errors will then be automatically localized when converted to strings.
Index ¶
- Variables
- type BaseValidator
- func (bv *BaseValidator) Custom(fn func(value interface{}, fieldName string) error) *BaseValidator
- func (bv *BaseValidator) Not() *BaseValidator
- func (bv *BaseValidator) Result() *ValidationResult
- func (bv *BaseValidator) Unless(condition func() bool) *BaseValidator
- func (bv *BaseValidator) Validate() error
- func (bv *BaseValidator) When(condition func() bool) *BaseValidator
- type Number
- type NumberValidator
- func Float32(value float32, fieldName string) *NumberValidator[float32]
- func Float64(value float64, fieldName string) *NumberValidator[float64]
- func Int(value int, fieldName string) *NumberValidator[int]
- func Int8(value int8, fieldName string) *NumberValidator[int8]
- func Int16(value int16, fieldName string) *NumberValidator[int16]
- func Int32(value int32, fieldName string) *NumberValidator[int32]
- func Int64(value int64, fieldName string) *NumberValidator[int64]
- func Numeric[T Number](value T, fieldName string) *NumberValidator[T]
- func Uint(value uint, fieldName string) *NumberValidator[uint]
- func Uint8(value uint8, fieldName string) *NumberValidator[uint8]
- func Uint16(value uint16, fieldName string) *NumberValidator[uint16]
- func Uint32(value uint32, fieldName string) *NumberValidator[uint32]
- func Uint64(value uint64, fieldName string) *NumberValidator[uint64]
- func (nv *NumberValidator[T]) Between(min, max T) *NumberValidator[T]
- func (nv *NumberValidator[T]) Custom(fn func(value interface{}, fieldName string) error) *NumberValidator[T]
- func (nv *NumberValidator[T]) Equal(expected T) *NumberValidator[T]
- func (nv *NumberValidator[T]) EqualTo(expected T, msgTemplate ...string) *NumberValidator[T]
- func (nv *NumberValidator[T]) Even() *NumberValidator[T]
- func (nv *NumberValidator[T]) Finite() *NumberValidator[T]
- func (nv *NumberValidator[T]) GreaterThan(value T) *NumberValidator[T]
- func (nv *NumberValidator[T]) In(values ...T) *NumberValidator[T]
- func (nv *NumberValidator[T]) LessThan(value T) *NumberValidator[T]
- func (nv *NumberValidator[T]) Max(max T) *NumberValidator[T]
- func (nv *NumberValidator[T]) Min(min T) *NumberValidator[T]
- func (nv *NumberValidator[T]) MultipleOf(divisor T) *NumberValidator[T]
- func (nv *NumberValidator[T]) Negative() *NumberValidator[T]
- func (nv *NumberValidator[T]) Not() *NumberValidator[T]
- func (nv *NumberValidator[T]) NotIn(values ...T) *NumberValidator[T]
- func (nv *NumberValidator[T]) Odd() *NumberValidator[T]
- func (nv *NumberValidator[T]) Positive() *NumberValidator[T]
- func (nv *NumberValidator[T]) Precision(places int) *NumberValidator[T]
- func (nv *NumberValidator[T]) Required() *NumberValidator[T]
- func (nv *NumberValidator[T]) Unless(condition func() bool) *NumberValidator[T]
- func (nv *NumberValidator[T]) When(condition func() bool) *NumberValidator[T]
- func (nv *NumberValidator[T]) Zero() *NumberValidator[T]
- type StringValidator
- func (sv *StringValidator) Alpha() *StringValidator
- func (sv *StringValidator) AlphaNumeric() *StringValidator
- func (sv *StringValidator) Base64() *StringValidator
- func (sv *StringValidator) Contains(substring string) *StringValidator
- func (sv *StringValidator) Custom(fn func(value interface{}, fieldName string) error) *StringValidator
- func (sv *StringValidator) Email() *StringValidator
- func (sv *StringValidator) Empty() *StringValidator
- func (sv *StringValidator) EndsWith(suffix string) *StringValidator
- func (sv *StringValidator) EqualTo(other string, msgTemplate ...string) *StringValidator
- func (sv *StringValidator) ExactLength(length int) *StringValidator
- func (sv *StringValidator) Float() *StringValidator
- func (sv *StringValidator) In(values ...string) *StringValidator
- func (sv *StringValidator) Integer() *StringValidator
- func (sv *StringValidator) JSON() *StringValidator
- func (sv *StringValidator) LengthBetween(min, max int) *StringValidator
- func (sv *StringValidator) Lowercase() *StringValidator
- func (sv *StringValidator) MaxLength(max int) *StringValidator
- func (sv *StringValidator) MinLength(min int) *StringValidator
- func (sv *StringValidator) Not() *StringValidator
- func (sv *StringValidator) NotIn(values ...string) *StringValidator
- func (sv *StringValidator) Numeric() *StringValidator
- func (sv *StringValidator) Regex(pattern *regexp.Regexp) *StringValidator
- func (sv *StringValidator) Required() *StringValidator
- func (sv *StringValidator) Slug() *StringValidator
- func (sv *StringValidator) StartsWith(prefix string) *StringValidator
- func (sv *StringValidator) URL() *StringValidator
- func (sv *StringValidator) UUID() *StringValidator
- func (sv *StringValidator) Unless(condition func() bool) *StringValidator
- func (sv *StringValidator) Uppercase() *StringValidator
- func (sv *StringValidator) When(condition func() bool) *StringValidator
- type ValidationOrchestrator
- func In(namespace string, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
- func InRow(namespace string, index int, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
- func Is(validators ...Validator) *ValidationOrchestrator
- func NewValidationOrchestrator() *ValidationOrchestrator
- func V() *ValidationOrchestrator
- func (vo *ValidationOrchestrator) ErrMap() map[string][]string
- func (vo *ValidationOrchestrator) Error() error
- func (vo *ValidationOrchestrator) FieldNames() []string
- func (vo *ValidationOrchestrator) GetFieldResult(fieldName string) *ValidationResult
- func (vo *ValidationOrchestrator) In(namespace string, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
- func (vo *ValidationOrchestrator) InRow(namespace string, index int, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
- func (vo *ValidationOrchestrator) Is(validators ...Validator) *ValidationOrchestrator
- func (vo *ValidationOrchestrator) IsValid(fieldName string) bool
- func (vo *ValidationOrchestrator) LocalizedErrMap(tag language.Tag) map[string][]string
- func (vo *ValidationOrchestrator) String() string
- func (vo *ValidationOrchestrator) ToJSON() ([]byte, error)
- func (vo *ValidationOrchestrator) Valid() bool
- type ValidationResult
- type Validator
- type ValidatorChain
Constants ¶
This section is empty.
Variables ¶
var ( EmailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`) URLRegex = regexp.MustCompile(`^https?://[^\s/$.?#].[^\s]*$`) NumericRegex = regexp.MustCompile(`^[0-9]+$`) AlphaRegex = regexp.MustCompile(`^[a-zA-Z]+$`) AlphaNumericRegex = regexp.MustCompile(`^[a-zA-Z0-9]+$`) )
Common validation patterns
Functions ¶
This section is empty.
Types ¶
type BaseValidator ¶
type BaseValidator struct {
// contains filtered or unexported fields
}
BaseValidator provides common functionality for all validators.
func NewBaseValidator ¶
func NewBaseValidator(value interface{}, fieldName string) *BaseValidator
NewBaseValidator creates a new BaseValidator.
func (*BaseValidator) Custom ¶
func (bv *BaseValidator) Custom(fn func(value interface{}, fieldName string) error) *BaseValidator
Custom validates using a custom validation function. The function receives both the value being validated and the field name, allowing for more contextual error messages.
Example:
err := vix.String("test", "username").
Custom(func(value interface{}, fieldName string) error {
str := value.(string)
if strings.Contains(str, "admin") {
return erm.NewValidationError("{{field}} cannot contain 'admin'", fieldName, value)
}
return nil
}).
Validate()
func (*BaseValidator) Not ¶
func (bv *BaseValidator) Not() *BaseValidator
Not negates the next validation rule.
func (*BaseValidator) Result ¶
func (bv *BaseValidator) Result() *ValidationResult
Result returns the full validation result.
func (*BaseValidator) Unless ¶
func (bv *BaseValidator) Unless(condition func() bool) *BaseValidator
Unless adds a condition that must be false for validation to run.
func (*BaseValidator) Validate ¶
func (bv *BaseValidator) Validate() error
Validate returns the validation result.
func (*BaseValidator) When ¶
func (bv *BaseValidator) When(condition func() bool) *BaseValidator
When adds a condition that must be true for validation to run.
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
Number defines a type constraint for all numeric types
type NumberValidator ¶
type NumberValidator[T Number] struct { *BaseValidator // contains filtered or unexported fields }
NumberValidator provides validation rules for numeric values. It supports method chaining for readable and maintainable validation.
func Float32 ¶
func Float32(value float32, fieldName string) *NumberValidator[float32]
Float32 creates a NumberValidator for float32 values.
func Float64 ¶
func Float64(value float64, fieldName string) *NumberValidator[float64]
Float64 creates a NumberValidator for float64 values.
func Int ¶
func Int(value int, fieldName string) *NumberValidator[int]
Int creates a NumberValidator for int values.
func Int8 ¶
func Int8(value int8, fieldName string) *NumberValidator[int8]
Int8 creates a NumberValidator for int8 values.
func Int16 ¶
func Int16(value int16, fieldName string) *NumberValidator[int16]
Int16 creates a NumberValidator for int16 values.
func Int32 ¶
func Int32(value int32, fieldName string) *NumberValidator[int32]
Int32 creates a NumberValidator for int32 values.
func Int64 ¶
func Int64(value int64, fieldName string) *NumberValidator[int64]
Int64 creates a NumberValidator for int64 values.
func Numeric ¶
func Numeric[T Number](value T, fieldName string) *NumberValidator[T]
Numeric creates a new NumberValidator for the given value and field name. This function uses Go generics to support all numeric types.
Example:
err := validator.Numeric(42, "age"). Min(18). Max(100). Validate()
func Uint ¶
func Uint(value uint, fieldName string) *NumberValidator[uint]
Uint creates a NumberValidator for uint values.
func Uint8 ¶
func Uint8(value uint8, fieldName string) *NumberValidator[uint8]
Uint8 creates a NumberValidator for uint8 values.
func Uint16 ¶
func Uint16(value uint16, fieldName string) *NumberValidator[uint16]
Uint16 creates a NumberValidator for uint16 values.
func Uint32 ¶
func Uint32(value uint32, fieldName string) *NumberValidator[uint32]
Uint32 creates a NumberValidator for uint32 values.
func Uint64 ¶
func Uint64(value uint64, fieldName string) *NumberValidator[uint64]
Uint64 creates a NumberValidator for uint64 values.
func (*NumberValidator[T]) Between ¶
func (nv *NumberValidator[T]) Between(min, max T) *NumberValidator[T]
Between validates that the number is between min and max (inclusive).
func (*NumberValidator[T]) Custom ¶
func (nv *NumberValidator[T]) Custom(fn func(value interface{}, fieldName string) error) *NumberValidator[T]
Custom validates using a custom validation function. The function receives both the numeric value being validated and the field name, allowing for more contextual error messages.
Example:
err := vix.Int(13, "age").
Custom(func(value interface{}, fieldName string) error {
age := value.(int)
if age == 13 {
return erm.NewValidationError("{{field}} cannot be unlucky number 13", fieldName, value)
}
return nil
}).
Validate()
func (*NumberValidator[T]) Equal ¶
func (nv *NumberValidator[T]) Equal(expected T) *NumberValidator[T]
Equal validates that the number equals the specified value.
func (*NumberValidator[T]) EqualTo ¶
func (nv *NumberValidator[T]) EqualTo(expected T, msgTemplate ...string) *NumberValidator[T]
EqualTo validates that the number equals the specified value. Optionally accepts a custom error message template as the second parameter. If no custom message is provided, uses the default localized message.
Example:
// With default message
err := vix.Int(25, "age").EqualTo(18).Validate()
// With custom message template
err = vix.Int(25, "age").
EqualTo(18, "{{field}} must be exactly {{expected}} years old").
Validate()
// Works with negation and different numeric types
err = vix.Float64(3.14, "pi").
Not().EqualTo(2.71).
Validate()
func (*NumberValidator[T]) Even ¶
func (nv *NumberValidator[T]) Even() *NumberValidator[T]
Even validates that the number is even.
func (*NumberValidator[T]) Finite ¶
func (nv *NumberValidator[T]) Finite() *NumberValidator[T]
Finite validates that the number is finite (for floating-point numbers).
func (*NumberValidator[T]) GreaterThan ¶
func (nv *NumberValidator[T]) GreaterThan(value T) *NumberValidator[T]
GreaterThan validates that the number is greater than the specified value.
func (*NumberValidator[T]) In ¶
func (nv *NumberValidator[T]) In(values ...T) *NumberValidator[T]
In validates that the number is one of the specified values.
func (*NumberValidator[T]) LessThan ¶
func (nv *NumberValidator[T]) LessThan(value T) *NumberValidator[T]
LessThan validates that the number is less than the specified value.
func (*NumberValidator[T]) Max ¶
func (nv *NumberValidator[T]) Max(max T) *NumberValidator[T]
Max validates that the number is less than or equal to the maximum value.
func (*NumberValidator[T]) Min ¶
func (nv *NumberValidator[T]) Min(min T) *NumberValidator[T]
Min validates that the number is greater than or equal to the minimum value.
func (*NumberValidator[T]) MultipleOf ¶
func (nv *NumberValidator[T]) MultipleOf(divisor T) *NumberValidator[T]
MultipleOf validates that the number is a multiple of the specified value.
func (*NumberValidator[T]) Negative ¶
func (nv *NumberValidator[T]) Negative() *NumberValidator[T]
Negative validates that the number is negative (less than zero).
func (*NumberValidator[T]) Not ¶
func (nv *NumberValidator[T]) Not() *NumberValidator[T]
Not negates the next validation rule.
func (*NumberValidator[T]) NotIn ¶
func (nv *NumberValidator[T]) NotIn(values ...T) *NumberValidator[T]
NotIn validates that the number is not one of the specified values.
func (*NumberValidator[T]) Odd ¶
func (nv *NumberValidator[T]) Odd() *NumberValidator[T]
Odd validates that the number is odd.
func (*NumberValidator[T]) Positive ¶
func (nv *NumberValidator[T]) Positive() *NumberValidator[T]
Positive validates that the number is positive (greater than zero).
func (*NumberValidator[T]) Precision ¶
func (nv *NumberValidator[T]) Precision(places int) *NumberValidator[T]
Precision validates that a float has at most the specified number of decimal places.
func (*NumberValidator[T]) Required ¶
func (nv *NumberValidator[T]) Required() *NumberValidator[T]
Required validates that the number is not zero.
func (*NumberValidator[T]) Unless ¶
func (nv *NumberValidator[T]) Unless(condition func() bool) *NumberValidator[T]
Unless adds a condition that must be false for validation to run.
func (*NumberValidator[T]) When ¶
func (nv *NumberValidator[T]) When(condition func() bool) *NumberValidator[T]
When adds a condition that must be true for validation to run.
func (*NumberValidator[T]) Zero ¶
func (nv *NumberValidator[T]) Zero() *NumberValidator[T]
Zero validates that the number is zero.
type StringValidator ¶
type StringValidator struct {
*BaseValidator
}
StringValidator provides validation rules for string values. It supports method chaining for readable and maintainable validation.
func String ¶
func String(value string, fieldName string) *StringValidator
String creates a new StringValidator for the given value and field name.
Example:
err := validator.String("john@example.com", "email").
Required().
Email().
MaxLength(100).
Validate()
func (*StringValidator) Alpha ¶
func (sv *StringValidator) Alpha() *StringValidator
Alpha validates that the string contains only alphabetic characters.
func (*StringValidator) AlphaNumeric ¶
func (sv *StringValidator) AlphaNumeric() *StringValidator
AlphaNumeric validates that the string contains only alphanumeric characters.
func (*StringValidator) Base64 ¶
func (sv *StringValidator) Base64() *StringValidator
Base64 validates that the string is valid base64.
func (*StringValidator) Contains ¶
func (sv *StringValidator) Contains(substring string) *StringValidator
Contains validates that the string contains the specified substring.
func (*StringValidator) Custom ¶
func (sv *StringValidator) Custom(fn func(value interface{}, fieldName string) error) *StringValidator
Custom validates using a custom validation function. The function receives both the string value being validated and the field name, allowing for more contextual error messages.
Example:
err := vix.String("test@admin.com", "email").
Custom(func(value interface{}, fieldName string) error {
str := value.(string)
if strings.HasSuffix(str, "@admin.com") {
return &ValidationError{Message: fieldName + " cannot use admin domain"}
}
return nil
}).
Validate()
func (*StringValidator) Email ¶
func (sv *StringValidator) Email() *StringValidator
Email validates that the string is a valid email address format.
func (*StringValidator) Empty ¶
func (sv *StringValidator) Empty() *StringValidator
Empty validates that the string is empty (exactly empty, not just whitespace).
func (*StringValidator) EndsWith ¶
func (sv *StringValidator) EndsWith(suffix string) *StringValidator
EndsWith validates that the string ends with the specified suffix.
func (*StringValidator) EqualTo ¶
func (sv *StringValidator) EqualTo(other string, msgTemplate ...string) *StringValidator
EqualTo validates that the string equals the specified value. Optionally accepts a custom error message template as the second parameter. If no custom message is provided, uses the default localized message.
Example:
// With default message
err := vix.String("john", "username").EqualTo("admin").Validate()
// With custom message template
err = vix.String("john", "username").
EqualTo("admin", "{{field}} must be exactly '{{expected}}'").
Validate()
// Works with negation
err = vix.String("admin", "username").
Not().EqualTo("root").
Validate()
func (*StringValidator) ExactLength ¶
func (sv *StringValidator) ExactLength(length int) *StringValidator
ExactLength validates that the string has exactly the specified number of characters.
func (*StringValidator) Float ¶
func (sv *StringValidator) Float() *StringValidator
Float validates that the string represents a valid floating-point number.
func (*StringValidator) In ¶
func (sv *StringValidator) In(values ...string) *StringValidator
In validates that the string is one of the specified values.
func (*StringValidator) Integer ¶
func (sv *StringValidator) Integer() *StringValidator
Integer validates that the string represents a valid integer.
func (*StringValidator) JSON ¶
func (sv *StringValidator) JSON() *StringValidator
JSON validates that the string is valid JSON.
func (*StringValidator) LengthBetween ¶
func (sv *StringValidator) LengthBetween(min, max int) *StringValidator
LengthBetween validates that the string length is between min and max (inclusive).
func (*StringValidator) Lowercase ¶
func (sv *StringValidator) Lowercase() *StringValidator
Lowercase validates that the string is in lowercase.
func (*StringValidator) MaxLength ¶
func (sv *StringValidator) MaxLength(max int) *StringValidator
MaxLength validates that the string has at most the specified number of characters.
func (*StringValidator) MinLength ¶
func (sv *StringValidator) MinLength(min int) *StringValidator
MinLength validates that the string has at least the specified number of characters.
func (*StringValidator) Not ¶
func (sv *StringValidator) Not() *StringValidator
Not negates the next validation rule.
func (*StringValidator) NotIn ¶
func (sv *StringValidator) NotIn(values ...string) *StringValidator
NotIn validates that the string is not one of the specified values.
func (*StringValidator) Numeric ¶
func (sv *StringValidator) Numeric() *StringValidator
Numeric validates that the string contains only numeric characters.
func (*StringValidator) Regex ¶
func (sv *StringValidator) Regex(pattern *regexp.Regexp) *StringValidator
Regex validates that the string matches the given regular expression.
func (*StringValidator) Required ¶
func (sv *StringValidator) Required() *StringValidator
Required validates that the string is not empty (after trimming whitespace).
func (*StringValidator) Slug ¶
func (sv *StringValidator) Slug() *StringValidator
Slug validates that the string is a valid URL slug.
func (*StringValidator) StartsWith ¶
func (sv *StringValidator) StartsWith(prefix string) *StringValidator
StartsWith validates that the string starts with the specified prefix.
func (*StringValidator) URL ¶
func (sv *StringValidator) URL() *StringValidator
URL validates that the string is a valid URL format.
func (*StringValidator) UUID ¶
func (sv *StringValidator) UUID() *StringValidator
UUID validates that the string is a valid UUID.
func (*StringValidator) Unless ¶
func (sv *StringValidator) Unless(condition func() bool) *StringValidator
Unless adds a condition that must be false for validation to run.
func (*StringValidator) Uppercase ¶
func (sv *StringValidator) Uppercase() *StringValidator
Uppercase validates that the string is in uppercase.
func (*StringValidator) When ¶
func (sv *StringValidator) When(condition func() bool) *StringValidator
When adds a condition that must be true for validation to run.
type ValidationOrchestrator ¶
type ValidationOrchestrator struct {
// contains filtered or unexported fields
}
ValidationOrchestrator manages multiple validators and provides a unified interface for validating multiple fields and creating comprehensive error reports. It supports namespace organization for nested structures and arrays.
The orchestrator collects validation results from multiple validators and provides methods to check validity, retrieve errors, and generate structured output suitable for API responses. All error messages are automatically localized through the ERM package's i18n system.
The orchestrator uses an erm.Error container internally to collect and manage all validation errors, leveraging ERM's error collection capabilities for efficient error handling and reporting.
func In ¶
func In(namespace string, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
In creates a new ValidationOrchestrator with a single namespaced validation orchestrator. This is a convenience function that allows you to write vix.In(...) instead of vix.V().In(...).
Example:
val := vix.In("address", vix.Is(
vix.String(address.Street, "street").Required(),
vix.String(address.City, "city").Required(),
))
func InRow ¶
func InRow(namespace string, index int, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
InRow creates a new ValidationOrchestrator with a single indexed namespaced validation orchestrator. This is a convenience function that allows you to write vix.InRow(...) instead of vix.V().InRow(...).
Example:
val := vix.InRow("addresses", 0, vix.Is(
vix.String(address.Street, "street").Required(),
vix.String(address.City, "city").Required(),
))
func Is ¶
func Is(validators ...Validator) *ValidationOrchestrator
Is creates a new ValidationOrchestrator and adds the given validators to it. This is a convenience function that allows you to write vix.Is(...) instead of vix.V().Is(...).
Example:
val := vix.Is(
vix.String("test@example.com", "email").Required().Email(),
vix.Int(25, "age").Required().Min(18),
)
if !val.Valid() {
errorMap := val.ErrMap()
// handle errors
}
func NewValidationOrchestrator ¶
func NewValidationOrchestrator() *ValidationOrchestrator
NewValidationOrchestrator creates a new ValidationOrchestrator.
func V ¶
func V() *ValidationOrchestrator
V creates a new ValidationOrchestrator. This is a shorthand function for convenience.
func (*ValidationOrchestrator) ErrMap ¶
func (vo *ValidationOrchestrator) ErrMap() map[string][]string
ErrMap returns a map of field names to error messages using the default localizer. Now leverages ERM's localized error map functionality while preserving the namespaced field names managed by the orchestrator.
func (*ValidationOrchestrator) Error ¶
func (vo *ValidationOrchestrator) Error() error
Error returns a single erm.Error containing all validation errors as children.
func (*ValidationOrchestrator) FieldNames ¶
func (vo *ValidationOrchestrator) FieldNames() []string
FieldNames returns all field names that have been validated.
func (*ValidationOrchestrator) GetFieldResult ¶
func (vo *ValidationOrchestrator) GetFieldResult(fieldName string) *ValidationResult
GetFieldResult returns the validation result for a specific field.
func (*ValidationOrchestrator) In ¶
func (vo *ValidationOrchestrator) In(namespace string, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
In adds validations within a namespace. The namespace is prefixed to field names.
func (*ValidationOrchestrator) InRow ¶
func (vo *ValidationOrchestrator) InRow(namespace string, index int, orchestrator *ValidationOrchestrator) *ValidationOrchestrator
InRow adds validations within an indexed namespace. The namespace and index are prefixed to field names.
func (*ValidationOrchestrator) Is ¶
func (vo *ValidationOrchestrator) Is(validators ...Validator) *ValidationOrchestrator
Is adds multiple validators to the orchestrator.
func (*ValidationOrchestrator) IsValid ¶
func (vo *ValidationOrchestrator) IsValid(fieldName string) bool
IsValid returns true if the specific field validation passed.
func (*ValidationOrchestrator) LocalizedErrMap ¶
func (vo *ValidationOrchestrator) LocalizedErrMap(tag language.Tag) map[string][]string
LocalizedErrMap returns a map of field names to localized error messages for the specified language. This provides full internationalization support while preserving the orchestrator's namespaced field structure.
func (*ValidationOrchestrator) String ¶
func (vo *ValidationOrchestrator) String() string
String returns a string representation of the validation state.
func (*ValidationOrchestrator) ToJSON ¶
func (vo *ValidationOrchestrator) ToJSON() ([]byte, error)
ToJSON returns the error map as JSON bytes.
func (*ValidationOrchestrator) Valid ¶
func (vo *ValidationOrchestrator) Valid() bool
Valid returns true if all validations passed.
type ValidationResult ¶
type ValidationResult struct {
Value interface{}
FieldName string
IsValid bool
// contains filtered or unexported fields
}
ValidationResult holds the result of a validation operation. It contains the original value, field name, and collects validation errors as a slice of erm.Error instances for unified error handling. Internationalization is handled automatically through the erm package. All validation errors use HTTP 400 Bad Request status code.
func NewValidationResult ¶
func NewValidationResult(value interface{}, fieldName string) *ValidationResult
NewValidationResult creates a new ValidationResult with the given value and field name.
func (*ValidationResult) AddError ¶
func (vr *ValidationResult) AddError(err error) *ValidationResult
AddError adds a validation error to the result.
func (*ValidationResult) AllErrors ¶
func (vr *ValidationResult) AllErrors() []erm.Error
AllErrors returns all validation errors.
func (*ValidationResult) ErrMap ¶
func (vr *ValidationResult) ErrMap() map[string][]string
ErrMap returns a map of field names to error messages. Returns nil if validation passed, otherwise returns the structured error map.
func (*ValidationResult) Error ¶
func (vr *ValidationResult) Error() error
Error returns the validation error container, or nil if validation passed.
func (*ValidationResult) Valid ¶
func (vr *ValidationResult) Valid() bool
Valid returns true if no validation errors occurred.
type Validator ¶
type Validator interface {
Validate() error
Result() *ValidationResult
}
Validator defines the interface that all validation rules must implement. It provides a single Validate method that returns an error if validation fails.
type ValidatorChain ¶
type ValidatorChain interface {
// Not negates the next validation rule
Not() ValidatorChain
// When adds a condition that must be true for validation to run
When(condition func() bool) ValidatorChain
// Unless adds a condition that must be false for validation to run
Unless(condition func() bool) ValidatorChain
// Custom validates using a custom validation function
Custom(fn func(value interface{}, fieldName string) error) ValidatorChain
}
ValidatorChain defines the interface for validator chaining operations. This interface eliminates code duplication by providing common methods that can be shared across different validator types.