validate

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package validate provides a unified validation service using go-playground/validator. The package supports locale-aware error messages (zh/en) and custom validation rules. Configuration via config.yaml:

验证服务包,使用 go-playground/validator 提供统一的参数校验能力。 支持本地化的错误消息(中文/英文)和自定义校验规则。 通过 config.yaml 配置:

validation:
  enabled: true
  locale: zh            # 错误消息语言(zh/en)
  translate_errors: true # 是否翻译错误(true=中文,false=英文原始错误,性能更好)

Eg:

// 注册 Provider
app.Register(validate.NewProvider())

// 使用验证服务
vSvc := c.MustMake(datacontract.ValidatorKey).(datacontract.Validator)
err := vSvc.Validate(ctx, &UserRequest{Name: "test", Email: "test@example.com"})

Package validate provides the validation service implementation. ValidatorService wraps validator.Validate with locale-aware error translation.

本文件提供验证服务实现,封装 go-playground/validator。 ValidatorService 封装 validator.Validate,支持本地化错误翻译。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Provider

type Provider struct{}

Provider registers the validation service contract.

Provider 注册验证服务契约。

func NewProvider

func NewProvider() *Provider

NewProvider creates a new validate provider instance.

NewProvider 创建新的验证 Provider 实例。

func (*Provider) Boot

Boot is a no-op for validate provider.

Boot 验证 Provider 无启动逻辑。

func (*Provider) IsDefer

func (p *Provider) IsDefer() bool

IsDefer returns true, validation can be deferred until first use.

IsDefer 返回 true,验证服务可延迟初始化。

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name "validate".

Name 返回 Provider 名称 "validate"。

func (*Provider) Provides

func (p *Provider) Provides() []string

Provides returns the validator contract key.

Provides 返回验证器契约键。

func (*Provider) Register

func (p *Provider) Register(c runtimecontract.Container) error

Register binds the validator service factory to the container.

Register 将验证服务工厂绑定到容器。

type ValidatorService

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

ValidatorService implements datacontract.Validator with go-playground/validator.

ValidatorService 使用 go-playground/validator 实现 datacontract.Validator 接口。

func NewValidatorService

func NewValidatorService(cfg *datacontract.ValidatorConfig) (*ValidatorService, error)

NewValidatorService creates a new validator service with given config. Core logic: Initialize validator, setup locale translator, register custom rules.

NewValidatorService 根据配置创建新的验证服务。 核心逻辑:初始化验证器、设置本地化翻译器、注册自定义规则。

func (*ValidatorService) GetTranslator

func (s *ValidatorService) GetTranslator() ut.Translator

GetTranslator returns the error translator for custom error formatting.

GetTranslator 返回错误翻译器,可用于自定义错误格式化。

func (*ValidatorService) GetValidator

func (s *ValidatorService) GetValidator() *validator.Validate

GetValidator returns the underlying validator.Validate instance.

GetValidator 返回底层的 validator.Validate 实例,用于高级自定义场景。

func (*ValidatorService) RegisterCustom

func (s *ValidatorService) RegisterCustom(name string, fn datacontract.CustomValidateFunc) error

RegisterCustom registers a custom validation rule. Eg:

RegisterCustom 注册自定义校验规则。 Eg:

err := vSvc.RegisterCustom("mobile", func(ctx context.Context, field interface{}) bool {
    return regexp.MustCompile(`^1[3-9]\d{9}$`).MatchString(fmt.Sprint(field))
})

func (*ValidatorService) SetLocale

func (s *ValidatorService) SetLocale(locale string) error

SetLocale changes the error translation locale (zh/en).

SetLocale 更改错误翻译的本地化语言(zh/en)。

func (*ValidatorService) TranslateError

func (s *ValidatorService) TranslateError(err error) error

TranslateError translates validation errors into localized AppError. Core logic: Check if error is ValidationErrors, then translate each field error. If TranslateErrors is false, returns raw English errors for better performance. Returns error interface; caller can cast to resiliencecontract.AppError if needed.

TranslateError 将验证错误翻译为本地化的 AppError。 核心逻辑:检查是否为 ValidationErrors 类型,然后翻译每个字段错误。 如果 TranslateErrors 为 false,返回原始英文错误以获得更好性能。 返回 error 接口;调用方可在需要时断言为 resiliencecontract.AppError。

func (*ValidatorService) Validate

func (s *ValidatorService) Validate(ctx context.Context, obj any) error

Validate validates a struct and returns translated errors. Eg:

Validate 校验结构体并返回翻译后的错误。 Eg:

type UserReq struct {
    Name  string `validate:"required"`
    Email string `validate:"required,email"`
}
err := vSvc.Validate(ctx, &UserReq{Name: "", Email: "invalid"})

func (*ValidatorService) ValidateVar

func (s *ValidatorService) ValidateVar(ctx context.Context, field any, tag string) error

ValidateVar validates a single variable against a tag. Eg:

ValidateVar 校验单个变量是否符合指定标签规则。 Eg:

err := vSvc.ValidateVar(ctx, "test@example.com", "required,email")

Directories

Path Synopsis
Package noop provides a no-op validator implementation for monolith scenarios.
Package noop provides a no-op validator implementation for monolith scenarios.

Jump to

Keyboard shortcuts

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