validation

package
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2025 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package validation provides validation utilities for the Midaz SDK.

This package contains functions for validating various aspects of Midaz data: - Transaction validation (DSL, standard inputs) - Asset code and type validation - Account alias and type validation - Metadata validation - Address validation - Date range validation

These utilities help ensure that data is valid before sending it to the API, providing early feedback and preventing unnecessary API calls with invalid data.

The package implements the functional options pattern for configuring validation behavior. Example:

validator, err := NewValidator(
    WithMaxMetadataSize(8192),
    WithStrictMode(true),
)
if err != nil {
    log.Fatal(err)
}

// Use the validator
if err := validator.ValidateMetadata(metadata); err != nil {
    log.Fatal(err)
}

Index

Constants

This section is empty.

Variables

View Source
var ErrMetadataSizeExceeded = &ValidationError{Message: "total metadata size exceeds maximum allowed size of 4KB"}

ErrMetadataSizeExceeded is returned when metadata exceeds the maximum allowed size

Functions

func GetCommonSuggestions

func GetCommonSuggestions(field string, value any, sugType SuggestionType) []string

GetCommonSuggestions returns suggestions for common validation issues

func GetExampleValue

func GetExampleValue(field string) string

GetExampleValue provides example values for common fields

func GetExternalAccountReference

func GetExternalAccountReference(assetCode string) string

GetExternalAccountReference creates a properly formatted external account reference for the given asset code

func IsValidAmount

func IsValidAmount(amount int64, scale int64) bool

IsValidAmount checks if an amount value is valid for a given scale.

func IsValidAuthToken

func IsValidAuthToken(token string) bool

IsValidAuthToken checks if a token has a valid format. This is a simple placeholder implementation; in a real-world scenario, you might perform more sophisticated validation.

func IsValidExternalAccountID

func IsValidExternalAccountID(id string) bool

IsValidExternalAccountID checks if an account ID is a valid external account ID.

func IsValidUUID

func IsValidUUID(s string) bool

IsValidUUID checks if a string is a valid UUID.

func ValidateAccountAlias

func ValidateAccountAlias(alias string) error

ValidateAccountAlias checks if an account alias is valid. Account aliases should be alphanumeric with optional underscores and hyphens.

Example:

if err := validation.ValidateAccountAlias("savings_account"); err != nil {
    log.Fatal(err)
}

func ValidateAccountType

func ValidateAccountType(accountType string) error

ValidateAccountType validates if the account type is one of the supported types in the Midaz system.

func ValidateAddress

func ValidateAddress(address *Address) error

ValidateAddress validates an address structure using the default validator. This function validates for completeness and correctness.

func ValidateAssetCode

func ValidateAssetCode(assetCode string) error

ValidateAssetCode checks if an asset code is valid. Asset codes should be 3-4 uppercase letters (e.g., USD, EUR, BTC).

Example:

if err := validation.ValidateAssetCode("USD"); err != nil {
    log.Fatal(err)
}

func ValidateAssetType

func ValidateAssetType(assetType string) error

ValidateAssetType validates if the asset type is one of the supported types in the Midaz system.

func ValidateCountryCode

func ValidateCountryCode(code string) error

ValidateCountryCode checks if the country code is valid according to ISO 3166-1 alpha-2.

func ValidateCurrencyCode

func ValidateCurrencyCode(code string) error

ValidateCurrencyCode checks if the currency code is valid according to ISO 4217.

func ValidateDateRange

func ValidateDateRange(start, end time.Time) error

ValidateDateRange checks if a date range is valid. The start date must not be after the end date.

Example:

start := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2023, 12, 31, 0, 0, 0, 0, time.UTC)
if err := validation.ValidateDateRange(start, end); err != nil {
    log.Fatal(err)
}

func ValidateMetadata

func ValidateMetadata(metadata map[string]any) error

ValidateMetadata checks if transaction metadata is valid with the default validator. This function verifies that metadata values are of supported types.

Example:

metadata := map[string]any{
    "reference": "inv123",
    "amount": 100.50,
    "customer_id": 12345,
}
if err := validation.ValidateMetadata(metadata); err != nil {
    log.Fatal(err)
}

func ValidateTransactionCode

func ValidateTransactionCode(code string) error

ValidateTransactionCode checks if a transaction code is valid. Transaction codes should be alphanumeric with optional underscores and hyphens.

Example:

if err := validation.ValidateTransactionCode("TX_123456"); err != nil {
    log.Fatal(err)
}

func ValidateTransactionDSL

func ValidateTransactionDSL(input TransactionDSLValidator) error

ValidateTransactionDSL performs pre-validation of transaction DSL input before sending to the API to catch common errors early

Types

type AccountReference

type AccountReference interface {
	GetAccount() string
}

AccountReference defines an interface for account references in transactions

type Address

type Address struct {
	Line1   string
	Line2   *string
	ZipCode string
	City    string
	State   string
	Country string
}

Address is a simplified address structure for validation purposes.

type FieldError

type FieldError struct {
	// Field is the path to the field that has a validation error
	// For nested fields, use dot notation (e.g., "metadata.user.address")
	Field string

	// Value is the invalid value that caused the error
	Value any

	// Message is a human-readable description of the error
	Message string

	// Code is an error code for programmatic error handling
	Code string

	// Constraint is the specific constraint that was violated (e.g., "required", "min", "max")
	Constraint string

	// Suggestions are potential ways to fix the error
	Suggestions []string
}

FieldError represents a validation error for a specific field with rich context and suggestions for fixing the problem.

func BuildFieldError

func BuildFieldError(field string, value any, message string) *FieldError

BuildFieldError creates a field error with common fields

func EnhancedValidateAccountAlias

func EnhancedValidateAccountAlias(alias string) *FieldError

EnhancedValidateAccountAlias checks if an account alias is valid and returns field-level errors with suggestions when invalid.

func EnhancedValidateAccountReference

func EnhancedValidateAccountReference(account string, transactionAsset string) *FieldError

EnhancedValidateAccountReference checks if an account reference is valid with enhanced error information, for both internal and external accounts

func EnhancedValidateAccountType

func EnhancedValidateAccountType(accountType string) *FieldError

EnhancedValidateAccountType checks if an account type is valid and returns field-level errors with suggestions when invalid.

func EnhancedValidateAmount

func EnhancedValidateAmount(amount, scale int64) *FieldError

EnhancedValidateAmount validates a transaction amount and returns field-level errors with suggestions when invalid.

func EnhancedValidateAssetCode

func EnhancedValidateAssetCode(assetCode string) *FieldError

EnhancedValidateAssetCode checks if an asset code is valid and returns field-level errors with suggestions when invalid.

func EnhancedValidateAssetType

func EnhancedValidateAssetType(assetType string) *FieldError

EnhancedValidateAssetType checks if an asset type is valid and returns field-level errors with suggestions when invalid.

func EnhancedValidateCountryCode

func EnhancedValidateCountryCode(code string) *FieldError

EnhancedValidateCountryCode validates a country code with enhanced error information

func EnhancedValidateCurrencyCode

func EnhancedValidateCurrencyCode(code string) *FieldError

EnhancedValidateCurrencyCode validates a currency code with enhanced error information

func EnhancedValidateExternalAccount

func EnhancedValidateExternalAccount(account string) *FieldError

EnhancedValidateExternalAccount checks if an external account reference is valid with enhanced error information

func EnhancedValidateExternalAccountWithTransactionAsset

func EnhancedValidateExternalAccountWithTransactionAsset(account string, transactionAsset string) *FieldError

EnhancedValidateExternalAccountWithTransactionAsset validates an external account with transaction asset

func EnhancedValidateTransactionCode

func EnhancedValidateTransactionCode(code string) *FieldError

EnhancedValidateTransactionCode checks if a transaction code is valid and returns field-level errors with suggestions when invalid.

func WrapError

func WrapError(field string, value any, err error) *FieldError

WrapError wraps a regular error as a field error

func (*FieldError) Error

func (fe *FieldError) Error() string

Error implements the error interface for FieldError

func (*FieldError) WithCode

func (fe *FieldError) WithCode(code string) *FieldError

WithCode adds an error code to a field error

func (*FieldError) WithConstraint

func (fe *FieldError) WithConstraint(constraint string) *FieldError

WithConstraint adds a constraint to a field error

func (*FieldError) WithSuggestions

func (fe *FieldError) WithSuggestions(suggestions ...string) *FieldError

WithSuggestions adds suggestions to a field error

type FieldErrors

type FieldErrors struct {
	Errors []*FieldError
}

FieldErrors represents a collection of field errors

func EnhancedValidateAddress

func EnhancedValidateAddress(address *Address, fieldPrefix string) *FieldErrors

EnhancedValidateAddress validates an address structure and returns field-level errors with suggestions when invalid.

func EnhancedValidateDateRange

func EnhancedValidateDateRange(start, end time.Time, startField, endField string) *FieldErrors

EnhancedValidateDateRange checks if a date range is valid and returns field-level errors with suggestions when invalid.

func EnhancedValidateMetadata

func EnhancedValidateMetadata(metadata map[string]any) *FieldErrors

EnhancedValidateMetadata checks if metadata is valid and returns field-level errors with suggestions when invalid.

func EnhancedValidateTransactionDSL

func EnhancedValidateTransactionDSL(input TransactionDSLValidator) *FieldErrors

EnhancedValidateTransactionDSL performs validation of transaction DSL input with enhanced error information

func EnhancedValidateTransactionInput

func EnhancedValidateTransactionInput(input map[string]any) *FieldErrors

EnhancedValidateTransactionInput validates a transaction input and returns field-level errors with suggestions when invalid.

func NewFieldErrors

func NewFieldErrors() *FieldErrors

NewFieldErrors creates a new empty FieldErrors collection

func (*FieldErrors) Add

func (fe *FieldErrors) Add(field string, value any, message string) *FieldError

Add adds a new field error to the collection

func (*FieldErrors) AddError

func (fe *FieldErrors) AddError(err *FieldError)

AddError adds an existing field error to the collection

func (*FieldErrors) Error

func (fe *FieldErrors) Error() string

Error implements the error interface for FieldErrors

func (*FieldErrors) GetErrorsForField

func (fe *FieldErrors) GetErrorsForField(field string) []*FieldError

GetErrorsForField returns all errors for a specific field

func (*FieldErrors) GetFieldErrors

func (fe *FieldErrors) GetFieldErrors() []*FieldError

GetFieldErrors returns all field errors in the collection

func (*FieldErrors) HasErrors

func (fe *FieldErrors) HasErrors() bool

HasErrors returns true if there are any errors in the collection

type SuggestionType

type SuggestionType string

SuggestionType represents the type of suggestion to provide

const (
	// Format issues
	Format SuggestionType = "format"

	// Required field issues
	Required SuggestionType = "required"

	// Range issues (min/max)
	Range SuggestionType = "range"

	// Enumeration issues (invalid value from a set)
	Enumeration SuggestionType = "enumeration"

	// Consistency issues (fields that must match)
	Consistency SuggestionType = "consistency"

	// Structural issues (missing or extra elements)
	Structure SuggestionType = "structure"
)

type TransactionDSLValidator

type TransactionDSLValidator interface {
	GetAsset() string
	GetValue() float64
	GetSourceAccounts() []AccountReference
	GetDestinationAccounts() []AccountReference
	GetMetadata() map[string]any
}

TransactionDSLValidator defines an interface for transaction DSL validation

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError represents a validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface

type ValidationSummary

type ValidationSummary struct {
	Valid  bool
	Errors []error
}

ValidationSummary holds the results of a validation operation with multiple potential errors

func ValidateCreateTransactionInput

func ValidateCreateTransactionInput(input map[string]any) ValidationSummary

ValidateCreateTransactionInput performs comprehensive validation on a transaction input Returns a validation summary with multiple errors if found

Example:

// Create a transaction
input := map[string]any{
	"amount": 10000,
	"scale":  2,
	"asset_code": "USD",
	"operations": []map[string]any{
		{
			"type":         "DEBIT",
			"account_id":   "acc_123",
			"account_alias": "savings",
			"amount":       10000,
		},
		{
			"type":         "CREDIT",
			"account_id":   "acc_456",
			"account_alias": "checking",
			"amount":       10000,
		},
	},
	"metadata": map[string]any{
		"reference": "TX-123456",
		"purpose": "Monthly transfer",
	},
}

// Validate the input
summary := validation.ValidateCreateTransactionInput(input)
if !summary.Valid {
	// Handle validation errors
	fmt.Println(summary.GetErrorSummary())
	return fmt.Errorf("transaction validation failed: %d errors found", len(summary.Errors))
}

// Proceed with creating the transaction

func (*ValidationSummary) AddError

func (vs *ValidationSummary) AddError(err error)

AddError adds an error to the validation summary and marks it as invalid

func (*ValidationSummary) GetErrorMessages

func (vs *ValidationSummary) GetErrorMessages() []string

GetErrorMessages returns all error messages as a slice of strings

func (*ValidationSummary) GetErrorSummary

func (vs *ValidationSummary) GetErrorSummary() string

GetErrorSummary returns a single string with all error messages

type Validator

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

Validator is a configurable validation instance that can be used to perform validations with specific configuration options.

func DefaultValidator

func DefaultValidator() *Validator

DefaultValidator returns a new validator with default configuration

func NewValidator

func NewValidator(options ...core.ValidationOption) (*Validator, error)

NewValidator creates a new Validator with the provided options

func (*Validator) ValidateAddress

func (v *Validator) ValidateAddress(address *Address) error

ValidateAddress validates an address structure using this validator's configuration. This method validates for completeness and correctness.

func (*Validator) ValidateMetadata

func (v *Validator) ValidateMetadata(metadata map[string]any) error

ValidateMetadata checks if transaction metadata is valid using this validator's configuration. This method verifies that metadata values are of supported types.

Directories

Path Synopsis
Package core provides fundamental validation utilities for the Midaz SDK.
Package core provides fundamental validation utilities for the Midaz SDK.

Jump to

Keyboard shortcuts

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