validator

package
v1.67.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 7 Imported by: 4

README

Package validator

Пакет validator предоставляет адаптер для валидации структур с использованием библиотеки github.com/txix-open/validator/v10 и поддержки перевода ошибок на английский язык.

Types

Adapter

Адаптер для валидации, инкапсулирующий валидатор и переводчик сообщений об ошибках.

Methods:

New() Adapter

Создаёт новый адаптер для валидатора с английским переводчиком.

Validate(v any) (ok bool, details map[string]string)

Проверяет структуру, возвращает true если валидация прошла успешно, иначе false и карту ошибок по полям.

ValidateToError(v any) error

Проверяет структуру, возвращает nil если ошибок нет, иначе объект ошибки с подробным описанием.

Usage

Default usage flow
package main

import (
	"fmt"
	"log"

	"github.com/txix-open/validator"
)

type User struct {
	Name  string `validate:"required"`
	Email string `validate:"required,email"`
	Age   int    `validate:"gte=0,lte=130"`
}

func main() {
	// Создаём адаптер валидатора с переводом ошибок на английский
	validator := validator.Default

	user := User{
		Name:  "",
		Email: "invalid-email",
		Age:   150,
	}

	ok, details := validator.Validate(user)
	if !ok {
		fmt.Println("Validation failed:")
		for field, errMsg := range details {
			fmt.Printf(" - %s: %s\n", field, errMsg)
		}
	} else {
		fmt.Println("Validation succeeded")
	}

	// Можно получить ошибку с описанием валидации
	err := validator.ValidateToError(user)
	if err != nil {
		log.Printf("Validation error: %v", err)
	}
}

Documentation

Overview

Package validator provides a structured validation adapter using the go-playground/validator library with English translations for error messages.

The package wraps the underlying validator to provide a simple API that returns validation results as a boolean flag and a map of field-specific error messages. It also provides a convenience method to convert validation failures to a single error with formatted field descriptions.

Example usage:

adapter := validator.New()
ok, details := adapter.Validate(myStruct)
if !ok {
    // details contains field -> error message mappings
}

Index

Constants

This section is empty.

Variables

View Source
var (
	Default = New()
)

Default is a globally available Adapter instance for quick validation without explicit initialization. It is safe for concurrent use.

Example usage:

ok, details := validator.Default.Validate(myStruct)

Functions

This section is empty.

Types

type Adapter

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

Adapter provides validation functionality with translated error messages. It wraps the go-playground/validator library and handles translation of validation errors into user-friendly messages.

func New

func New() Adapter

New creates a new Adapter instance with English translation support. The returned Adapter is safe for concurrent use.

func (Adapter) Validate

func (a Adapter) Validate(v any) (ok bool, details map[string]string)

Validate checks if the provided value passes all validation rules. It returns true and nil details if validation succeeds, or false and a map of field names to error messages if validation fails. The value should be a struct with validator tags defined on its fields. Returns an error in the details map under "#validator" key if an unexpected error occurs during validation.

func (Adapter) ValidateToError

func (a Adapter) ValidateToError(v any) error

ValidateToError validates the provided value and returns an error if validation fails. Returns nil if validation succeeds. The error message contains semicolon-separated field -> error message pairs for all validation failures.

Jump to

Keyboard shortcuts

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