validator

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 9 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Validator is the global validator instance from go-playground/validator.
	// It is initialized automatically and can be used throughout the application.
	Validator *validator.Validate

	// DefaultMessages contains fallback validation error messages in English.
	// These are used when i18nManager is not set or translation is not found.
	// Message templates use placeholders: {{.FieldName}}, {{.Param}}, {{.Tag}}
	DefaultMessages = map[string]string{
		"required": "{{.FieldName}} is required",
		"email":    "{{.FieldName}} must be a valid email address",
		"min":      "{{.FieldName}} must be at least {{.Param}} characters",
		"max":      "{{.FieldName}} must be at most {{.Param}} characters",
		"gte":      "{{.FieldName}} must be greater than or equal to {{.Param}}",
		"lte":      "{{.FieldName}} must be less than or equal to {{.Param}}",
		"len":      "{{.FieldName}} must be exactly {{.Param}} characters",
		"numeric":  "{{.FieldName}} must be numeric",
		"alphanum": "{{.FieldName}} must contain only letters and numbers",
		"default":  "{{.FieldName}} is invalid ({{.Tag}})",
	}
)

Functions

func SetI18nManager

func SetI18nManager(manager *i18n.I18nManager)

SetI18nManager sets the global I18nManager instance for validator translations. Once set, all validation error messages will use i18n translations with the "validator." prefix. If not set, validator will use DefaultMessages (English).

Parameters:

  • manager: *i18n.I18nManager - The initialized i18n manager instance

Example:

i18nMgr, _ := i18n.NewI18nManager(config)
validator.SetI18nManager(i18nMgr)

func ValidateStruct

func ValidateStruct(s interface{}) error

ValidateStruct validates a struct using validation tags with the default language. If i18nManager is set, it uses the default language from i18nManager. Otherwise, it uses "en" (English) as the default language.

Parameters:

  • s: The struct to validate (must have validation tags)

Returns:

  • error: nil if validation succeeds, *ValidationError if validation fails

Example:

type User struct {
    Email    string `validate:"required,email"`
    Password string `validate:"required,min=8"`
}

user := User{Email: "invalid", Password: "123"}
if err := ValidateStruct(user); err != nil {
    if verr, ok := err.(*ValidationError); ok {
        fmt.Println(verr.First())
        // Output: Email must be a valid email address
    }
}

func ValidateStructWithContext

func ValidateStructWithContext(c *fiber.Ctx, s interface{}) error

ValidateStructWithContext validates a struct using validation tags with language from Fiber context. It extracts the language from the Fiber context (set by I18nMiddleware) and uses it for error messages. If language is not found in context, it falls back to the default language.

The function automatically converts field names to title case for better readability. If i18nManager is set, it will use i18n translations from locale files with "validator." prefix. Otherwise, it falls back to DefaultMessages (English).

Parameters:

  • c: *fiber.Ctx - The Fiber context containing language information
  • s: The struct to validate (must have validation tags)

Returns:

  • error: nil if validation succeeds, *ValidationError if validation fails

Example:

app.Post("/users", func(c *fiber.Ctx) error {
    var user User
    if err := c.BodyParser(&user); err != nil {
        return err
    }

    if err := ValidateStructWithContext(c, user); err != nil {
        if verr, ok := err.(*ValidationError); ok {
            return c.Status(400).JSON(fiber.Map{
                "error": verr.First(),
            })
        }
    }

    return c.JSON(user)
})

func ValidateStructWithLang

func ValidateStructWithLang(s interface{}, lang string) error

ValidateStructWithLang validates a struct using validation tags with a specified language. It uses the global Validator instance and translates errors based on the specified language.

The function automatically converts field names to title case for better readability. If i18nManager is set, it will use i18n translations from locale files with "validator." prefix. Otherwise, it falls back to DefaultMessages (English).

If validation succeeds, it returns nil. If validation fails, it returns a ValidationError containing all validation error messages in the specified language.

Parameters:

  • s: The struct to validate (must have validation tags)
  • lang: Language code for error messages (e.g., "en", "id", "zh")

Returns:

  • error: nil if validation succeeds, *ValidationError if validation fails

Example:

type User struct {
    Email    string `validate:"required,email"`
    Password string `validate:"required,min=8"`
    Age      int    `validate:"gte=18"`
}

user := User{Email: "invalid", Password: "123", Age: 15}
if err := ValidateStructWithLang(user, "id"); err != nil {
    if verr, ok := err.(*ValidationError); ok {
        fmt.Println(verr.First())
        // Output: Email harus berupa alamat email yang valid
    }
}

Types

type ValidationError

type ValidationError struct {
	Messages []string            // All error messages (backward compatibility)
	Errors   map[string][]string // Field name -> error messages mapping
}

ValidationError is a custom error type for validation failures. It collects multiple validation error messages and provides convenient methods to access them individually or as a group, including per-field error details.

Fields:

  • Messages: Slice of all validation error messages (for backward compatibility)
  • Errors: Map of field names to their error messages (for detailed error reporting)

Methods:

  • Error(): Returns all messages joined by semicolon (implements error interface)
  • First(): Returns the first error message
  • All(): Returns all error messages as a slice
  • GetFieldErrors(): Returns map of field names to their error messages

Example:

if err := ValidateStruct(user, "en"); err != nil {
    if verr, ok := err.(*ValidationError); ok {
        fmt.Println(verr.First())  // Get first error
        fmt.Println(verr.All())    // Get all errors
        fmt.Println(verr.GetFieldErrors())  // Get errors per field
    }
}

func (*ValidationError) All

func (ve *ValidationError) All() []string

All returns all validation error messages as a slice.

Returns:

  • []string: Slice containing all error messages

Example:

verr := &ValidationError{Messages: []string{"Email is required", "Password is too short"}}
for _, msg := range verr.All() {
    fmt.Println(msg)
}
// Output:
// Email is required
// Password is too short

func (*ValidationError) Error

func (ve *ValidationError) Error() string

Error implements the error interface for ValidationError. It returns all validation error messages joined by semicolons.

Returns:

  • string: All error messages concatenated with "; " separator

Example:

verr := &ValidationError{Messages: []string{"Email is required", "Password is too short"}}
fmt.Println(verr.Error())
// Output: Email is required; Password is too short

func (*ValidationError) First

func (ve *ValidationError) First() string

First returns the first validation error message. If there are no error messages, it returns an empty string.

Returns:

  • string: First error message, or empty string if no messages exist

Example:

verr := &ValidationError{Messages: []string{"Email is required", "Password is too short"}}
fmt.Println(verr.First())
// Output: Email is required

func (*ValidationError) GetFieldErrors

func (ve *ValidationError) GetFieldErrors() map[string][]string

GetFieldErrors returns a map of field names to their error messages. This is useful for displaying field-specific errors in UI forms.

Returns:

  • map[string][]string: Map where keys are field names and values are slices of error messages for that field

Example:

verr := &ValidationError{
    Errors: map[string][]string{
        "Email": {"Email is required", "Email must be valid"},
        "Password": {"Password is too short"},
    },
}
for field, errs := range verr.GetFieldErrors() {
    fmt.Printf("%s: %v\n", field, errs)
}

Jump to

Keyboard shortcuts

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