validation

package
v14.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package validation provides generic field validation utilities for the Iris web framework. It offers type-safe validation functions and error handling for common validation scenarios including string, numeric, slice, and custom validation patterns.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Email

func Email(email string) string

Email accepts any string and returns a message if the value is not a valid email address.

func FormatPhoneNumber

func FormatPhoneNumber(phone string, format PhoneType) (string, bool)

FormatPhoneNumber attempts to format a phone number into a standardized format Returns the formatted phone number and a bool indicating success

func FormatRange

func FormatRange[T NumberType](min, max T) string

FormatRange returns a string representation of a range of values, such as "[1, 10]". It uses the NumberType constraint, which means that the parameters must be numeric types that support comparison and formatting operations.

func Fullname

func Fullname(s string) string

Fullname accepts any string and returns a message if the value is not a full name.

func InRange

func InRange[T NumberType](min, max T) func(T) string

InRange accepts any numeric type and returns a message if the value is not in the range.

func Join

func Join(errs ...errors.ValidationError) error

Join combines multiple validation errors into a single error, filtering out nil errors and errors with empty reasons. This function is essential for collecting validation results from multiple fields and presenting them as a unified validation failure.

The function returns the standard error interface rather than ValidationError to ensure proper nil handling. When all validation errors are nil or empty, Join returns nil instead of an empty ValidationErrors slice, preventing false positive error conditions.

Example usage:

// Validate multiple fields
emailErr := validation.Field("email", user.Email).Func(validation.Email)
passwordErr := validation.Field("password", user.Password).Func(validation.NotEmpty)
ageErr := validation.Field("age", user.Age).Func(validation.InRange(0, 150))

// Combine all validation errors
if err := validation.Join(emailErr, passwordErr, ageErr); err != nil {
    return errors.BadRequest.Validation(err)
}

// All validations passed
return nil

When multiple errors are present, the resulting error message will be formatted as:

"[0] email validation error, [1] password validation error, [2] age validation error"

This function is particularly useful in complex validation scenarios where multiple fields need to be validated independently, and all validation failures should be reported together for better user experience.

func Negative

func Negative[T NumberType](n T) string

Negative accepts any numeric type and returns a message if the value is not negative.

func NonZero

func NonZero[T NumberType](n T) string

NonZero accepts any numeric type and returns a message if the value is zero.

func NotEmpty

func NotEmpty(s string) string

NotEmpty accepts any string and returns a message if the value is empty.

func NotEmptySlice

func NotEmptySlice[T any, V SliceType[T]](s V) string

NotEmptySlice accepts any slice and returns a message if the value is empty.

func PhoneNumber

func PhoneNumber(phoneType PhoneType) func(string) string

PhoneNumber validates that a string represents a valid phone number according to the specified format.

The function accepts a PhoneType parameter that determines the validation rules:

PhoneAny (default): Accepts any reasonable phone number format with 7-15 digits.

Examples:
  - "555-123-4567"
  - "(555) 123-4567"
  - "+1 555 123 4567"
  - "5551234567"

PhoneE164: Validates according to the E.164 international standard format.

This format requires a + prefix followed by the country code and subscriber number,
with no spaces, dashes, or other formatting characters.
Examples:
  - "+15551234567" (US/Canada)
  - "+442079460958" (UK)
  - "+61291234567" (Australia)

PhoneNorthAmerican: Validates according to the North American Numbering Plan.

Requires a 3-digit area code (first digit 2-9) and a 7-digit local number (first digit of prefix 2-9).
Examples:
  - "(555) 123-4567"
  - "555-123-4567"
  - "5551234567"
  - "+1 (555) 123-4567"

PhoneInternational: Validates international phone numbers with country codes.

Must start with a + or 00, followed by the country code and subscriber number.
Examples:
  - "+44 20 7946 0958" (UK)
  - "+61 2 9123 4567" (Australia)
  - "+49 30 12345678" (Germany)

Returns an empty string if valid, or an error message if invalid. PhoneNumber validates that a string represents a valid phone number according to the specified format.

func Positive

func Positive[T NumberType](n T) string

Positive accepts any numeric type and returns a message if the value is not positive.

func SliceLength

func SliceLength[T any, V SliceType[T]](min, max int) func(s V) string

SliceLength accepts any slice and returns a message if the length is not in the given range.

func StringLength

func StringLength(min, max int) func(s string) string

StringLength accepts any string and returns a message if the length is not in the given range.

func StrongPassword

func StrongPassword(password string, requiredLevel PasswordStrengthLevel) string

StrongPassword accepts a password and a required strength level and returns a message if the password doesn't meet the required strength.

func Zero

func Zero[T NumberType](n T) string

Zero accepts any numeric type and returns a message if the value is not zero.

Types

type FieldError

type FieldError[T any] struct {
	// Field contains the name of the field being validated.
	// This helps identify which specific field failed validation in complex data structures.
	Field string `json:"field"`

	// Value contains the actual value that failed validation.
	// The type T ensures type safety and allows for precise error reporting.
	Value T `json:"value"`

	// Reason contains the human-readable explanation of why validation failed.
	// This message should be clear and actionable for end users.
	Reason string `json:"reason"`
}

FieldError represents a generic field validation error with type safety for the field value. It implements the errors.ValidationError interface and reports the field name, the actual value and the reason the value was rejected.

FieldError uses Go generics to maintain type safety for field values while providing a consistent validation error structure. This allows for precise error reporting and debugging while maintaining compile-time type checking.

Example usage:

// String field validation
emailField := validation.Field("email", "invalid-email")
emailField.Func(validation.Email)
if err := emailField.Get(); err != nil {
    return errors.BadRequest.Validation(err)
}

// Numeric field validation
ageField := validation.Field("age", -5)
ageField.Func(validation.InRange(0, 150))
if err := ageField.Get(); err != nil {
    return errors.BadRequest.Validation(err)
}

// Custom validation
passwordField := validation.Field("password", "123")
passwordField.Func(func(value string) string {
    if len(value) < 8 {
        return "must be at least 8 characters long"
    }
    return ""
})

The FieldError struct can be serialized to JSON for API responses, providing structured error information to clients.

func Field

func Field[T any](field string, value T) *FieldError[T]

Field creates a new FieldError instance for the specified field name and value. This is the primary constructor for field validation and should be used as the starting point for all field validation operations.

The function uses Go generics to ensure type safety for the field value, allowing validation functions to work with strongly-typed values while maintaining error reporting consistency.

Example usage:

// Create field validators for different types
emailField := validation.Field("email", user.Email)
ageField := validation.Field("age", user.Age)
tagsField := validation.Field("tags", user.Tags)

// Chain validation functions
emailField.Func(validation.NotEmpty, validation.Email)
ageField.Func(validation.InRange(18, 99))
tagsField.Func(validation.SliceLength[string, []string](1, 10))

After creating a field validator, use the Func method to apply validation rules, then call Get() to retrieve any validation errors.

func (*FieldError[T]) Error

func (e *FieldError[T]) Error() string

Error implements the standard error interface, providing a formatted string representation of the validation failure. The error message includes the field name, the actual value and the reason, which is what you need when debugging.

The format follows the pattern:

field "fieldname" got invalid value of actualvalue: reason: validation reason

Example output:

field "email" got invalid value of invalid-email: reason: must be a valid email address
field "age" got invalid value of -5: reason: must be greater than or equal to 0

func (*FieldError[T]) Func

func (e *FieldError[T]) Func(fns ...func(value T) string) *FieldError[T]

Func applies one or more validation functions to the field value and accumulates any validation failure reasons. Each validation function receives the field value and returns an empty string for successful validation or an error message for failures.

Multiple validation functions can be chained together, and all failure reasons are joined with commas, so a field that breaks several rules reports all of them at once.

The method returns the FieldError instance to enable method chaining for fluent validation syntax.

Example usage:

// Single validation function
emailField := validation.Field("email", user.Email)
emailField.Func(validation.Email)

// Multiple validation functions
passwordField := validation.Field("password", user.Password)
passwordField.Func(
    validation.NotEmpty,
    validation.StringLength(8, 128),
    func(value string) string {
        return validation.StrongPassword(value, validation.PasswordStrong)
    },
)

// Custom validation functions
usernameField := validation.Field("username", user.Username)
usernameField.Func(
    validation.NotEmpty,
    func(value string) string {
        if strings.Contains(value, " ") {
            return "must not contain spaces"
        }
        return ""
    },
    func(value string) string {
        if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(value) {
            return "must contain only letters, numbers, and underscores"
        }
        return ""
    },
)

If multiple validation functions fail, their reasons are joined:

"is required, must be at least 8 characters, must contain at least one uppercase letter"

func (*FieldError[T]) Get

func (e *FieldError[T]) Get() error

Get returns the FieldError as an error if validation failed, or nil if validation passed. This method should be called after applying validation functions to check if any validation rules were violated.

The method returns nil if the FieldError has no validation reason, indicating that all validation rules passed successfully. This allows for clean error handling patterns where only failed validations propagate as errors.

Example usage:

emailField := validation.Field("email", user.Email)
emailField.Func(validation.NotEmpty, validation.Email)

if err := emailField.Get(); err != nil {
    return errors.BadRequest.Validation(err)
}

// Validation passed, continue processing
return nil

func (*FieldError[T]) GetField

func (e *FieldError[T]) GetField() string

GetField returns the name of the field being validated. This method is part of the extended ValidationError interface and provides access to field metadata for error processing and response generation.

Field names should follow consistent naming conventions to ensure predictable error handling and client-side error processing.

func (*FieldError[T]) GetReason

func (e *FieldError[T]) GetReason() string

GetReason implements the errors.ValidationError interface, returning the human-readable explanation of why validation failed. This message should be suitable for display to end users and provide clear guidance on how to correct the validation error.

Example reasons:

  • "is required"
  • "must be a valid email address"
  • "must be between 8 and 32 characters"
  • "must contain at least one uppercase letter"

func (*FieldError[T]) GetValue

func (e *FieldError[T]) GetValue() any

GetValue returns the actual value that failed validation as an any. This method provides access to the field value for logging, debugging, and custom error processing scenarios.

The value is returned as any to satisfy the ValidationError interface while maintaining the original type information within the FieldError struct.

func (*FieldError[T]) IsZero

func (e *FieldError[T]) IsZero() bool

IsZero reports whether the FieldError represents a successful validation. A FieldError is considered "zero" (successful) if it is nil or has an empty validation reason, indicating that no validation rules were violated.

This method is used internally by Get() to determine whether to return an error and can be used in validation logic to check validation status without converting to an error interface.

Example usage:

field := validation.Field("username", user.Username)
field.Func(validation.NotEmpty, validation.StringLength(3, 0))

if !field.IsZero() {
    log.Printf("Validation failed: %s", field.GetReason())
}

type NumberError

type NumberError[T NumberType] struct{ *FieldError[T] }

NumberError describes a number field validation error.

func Number

func Number[T NumberType](field string, value T) *NumberError[T]

Number returns a new number validation error.

func (*NumberError[T]) InRange

func (e *NumberError[T]) InRange(min, max T) *NumberError[T]

InRange adds an error if the value is not in the range.

func (*NumberError[T]) Negative

func (e *NumberError[T]) Negative() *NumberError[T]

Negative adds an error if the value is not negative.

func (*NumberError[T]) NonZero

func (e *NumberError[T]) NonZero() *NumberError[T]

NonZero adds an error if the value is zero.

func (*NumberError[T]) Positive

func (e *NumberError[T]) Positive() *NumberError[T]

Positive adds an error if the value is not positive.

func (*NumberError[T]) Zero

func (e *NumberError[T]) Zero() *NumberError[T]

Zero adds an error if the value is not zero.

type NumberType

type NumberType interface {
	constraints.Number
}

NumberType is a type constraint that accepts any numeric type.

type PasswordStrength

type PasswordStrength struct {
	HasUpper   bool
	HasLower   bool
	HasNumber  bool
	HasSpecial bool
	Length     int
}

PasswordStrength holds information about the password strength criteria

type PasswordStrengthLevel

type PasswordStrengthLevel string

PasswordStrengthLevel represents the required strength of a password

const (
	// Password strength levels
	PasswordVeryWeak   PasswordStrengthLevel = "very weak"   // Length >= 4
	PasswordWeak       PasswordStrengthLevel = "weak"        // Length >= 8, 1 category
	PasswordMedium     PasswordStrengthLevel = "medium"      // Length >= 8, 2 categories
	PasswordStrong     PasswordStrengthLevel = "strong"      // Length >= 10, 3 categories
	PasswordVeryStrong PasswordStrengthLevel = "very strong" // Length >= 12, all categories
)

type PhoneType

type PhoneType string

PhoneType represents different phone number format standards

const (
	PhoneAny           PhoneType = "any"            // Any reasonable phone format
	PhoneE164          PhoneType = "e164"           // E.164 international format
	PhoneNorthAmerican PhoneType = "north_american" // North American numbering plan
	PhoneInternational PhoneType = "international"  // International format with country code
)

func ParsePhoneType

func ParsePhoneType(pt string) PhoneType

ParsePhoneType converts a string representation of a phone type into a PhoneType constant. It supports "e164", "north_american" (or "us"), and "international".

type SliceError

type SliceError[T any, V SliceType[T]] struct{ *FieldError[V] }

SliceError describes a slice field validation error.

func Slice

func Slice[T any, V SliceType[T]](field string, value V) *SliceError[T, V]

Slice returns a new slice validation error.

func (*SliceError[T, V]) Length

func (e *SliceError[T, V]) Length(min, max int) *SliceError[T, V]

Length adds an error if the slice length is not in the given range.

func (*SliceError[T, V]) NotEmpty

func (e *SliceError[T, V]) NotEmpty() *SliceError[T, V]

NotEmpty adds an error if the slice is empty.

type SliceType

type SliceType[T any] interface {
	~[]T
}

SliceType is a type constraint that accepts any slice type.

type StringError

type StringError struct{ *FieldError[string] }

StringError describes a string field validation error.

func String

func String(field string, value string) *StringError

String returns a new string validation error.

func (*StringError) Email

func (e *StringError) Email() *StringError

Email adds an error if the string is not a valid email address.

func (*StringError) Fullname

func (e *StringError) Fullname() *StringError

Fullname adds an error if the string is not a full name.

func (*StringError) Length

func (e *StringError) Length(min, max int) *StringError

Length adds an error if the string length is not in the given range.

func (*StringError) NotEmpty

func (e *StringError) NotEmpty() *StringError

NotEmpty adds an error if the string is empty.

func (*StringError) Password

func (e *StringError) Password(requiredLevel PasswordStrengthLevel) *StringError

Password adds a password strength validation to a StringError

func (*StringError) Phone

func (e *StringError) Phone(phoneType PhoneType) *StringError

Phone adds an error if the string is not a valid phone number of the given type.

Jump to

Keyboard shortcuts

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