validation

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 9 Imported by: 0

README

validation 包 — 数据验证

所属层级: Infrastructure Layer
设计理念: 声明式验证,灵活扩展
设计灵感: Spring Validation + Bean Validation

概述

validation 包提供灵活的数据验证能力,支持 HTTP 请求验证和结构体验证。支持多种验证类型,包括必填、字符串长度、数值范围、邮箱格式、正则表达式、枚举值等。

核心功能
功能 说明
声明式验证 通过配置规则实现验证逻辑与业务代码分离
多种验证类型 支持 required、string、number、email、regex、enum 等
HTTP 请求验证 支持 query、header、body 验证
快速失败模式 支持遇到第一个错误就停止验证
自定义错误消息 支持友好的错误提示
线程安全 验证器创建后只读,支持并发使用

核心接口

ValidationRule 验证规则
type ValidationRule struct {
    Field     string   // 字段名称
    Type      string   // 验证类型:required, string, number, email, regex, enum, min, max, length
    Value     string   // 验证值(用于 enum, regex 等)
    Min       *float64 // 最小值
    Max       *float64 // 最大值
    MinLength *int     // 最小长度
    MaxLength *int     // 最大长度
    Pattern   string   // 正则表达式
    Message   string   // 自定义错误消息
    In        []string // 枚举值
}
ValidationConfig 验证配置
type ValidationConfig struct {
    Rules    []ValidationRule // 验证规则
    Source   string           // 验证来源:query, header, body
    FailFast bool             // 快速失败(遇到第一个错误就停止)
}
验证结果
type RuleValidationResult struct {
    Valid  bool                // 是否通过验证
    Errors []RuleValidationError // 错误列表
}

type RuleValidationError struct {
    Field   string // 字段名称
    Message string // 错误消息
    Type    string // 错误类型
}

验证类型

1. required — 必填

验证字段不能为空:

rule := validation.ValidationRule{
    Field: "name",
    Type:  "required",
}
2. string — 字符串验证

验证字符串长度:

minLen := 2
maxLen := 50
rule := validation.ValidationRule{
    Field:     "name",
    Type:      "string",
    MinLength: &minLen,
    MaxLength: &maxLen,
}
3. number — 数值验证

验证数值范围:

minVal := 1.0
maxVal := 100.0
rule := validation.ValidationRule{
    Field: "age",
    Type:  "number",
    Min:   &minVal,
    Max:   &maxVal,
}
4. email — 邮箱验证

验证邮箱格式:

rule := validation.ValidationRule{
    Field: "email",
    Type:  "email",
}
5. regex — 正则表达式验证

使用正则表达式验证格式:

rule := validation.ValidationRule{
    Field:   "phone",
    Type:    "regex",
    Pattern: `^\d{3}-\d{3}-\d{4}$`,
}
6. enum — 枚举值验证

验证值是否在允许的枚举值中:

rule := validation.ValidationRule{
    Field: "status",
    Type:  "enum",
    In:    []string{"active", "inactive", "pending"},
}
7. min — 最小值验证

验证数值不小于最小值:

minVal := 0.0
rule := validation.ValidationRule{
    Field: "price",
    Type:  "min",
    Min:   &minVal,
}
8. max — 最大值验证

验证数值不大于最大值:

maxVal := 1000.0
rule := validation.ValidationRule{
    Field: "quantity",
    Type:  "max",
    Max:   &maxVal,
}
9. length — 长度验证

验证字符串长度范围:

minLen := 6
maxLen := 20
rule := validation.ValidationRule{
    Field:     "password",
    Type:      "length",
    MinLength: &minLen,
    MaxLength: &maxLen,
}

快速开始

基本验证
package main

import (
    "fmt"
    "github.com/xudefa/enhance/validation"
)

func main() {
    rules := []validation.ValidationRule{
        {Field: "name", Type: "required"},
        {Field: "email", Type: "email"},
        {Field: "age", Type: "number", Min: floatPtr(18), Max: floatPtr(100)},
    }

    body := []byte(`{"name":"test","email":"test@example.com","age":25}`)
    result := validation.ValidateJSONBody(body, rules)
    
    if !result.Valid {
        for _, e := range result.Errors {
            fmt.Printf("Field: %s, Error: %s\n", e.Field, e.Message)
        }
    }
}

API 参考

RequestValidator 请求验证器

创建可复用的请求验证器:

config := validation.ValidationConfig{
    Source: "query",
    Rules: []validation.ValidationRule{
        {Field: "page", Type: "required"},
        {Field: "size", Type: "number", Min: floatPtr(1), Max: floatPtr(100)},
    },
    FailFast: false,
}

validator, err := validation.NewRequestValidator(config)
if err != nil {
    // 处理配置错误(如无效的正则表达式)
}

// 验证请求
result := validator.Validate(req)
if !result.Valid {
    for _, e := range result.Errors {
        fmt.Printf("Field: %s, Error: %s\n", e.Field, e.Message)
    }
}
ValidateQuery 快速验证查询参数
rules := []validation.ValidationRule{
    {Field: "page", Type: "required"},
    {Field: "size", Type: "number", Min: floatPtr(1), Max: floatPtr(100)},
}

result := validation.ValidateQuery(req, rules)
if !result.Valid {
    // 处理验证错误
}
ValidateHeaders 快速验证请求头
rules := []validation.ValidationRule{
    {Field: "X-Api-Key", Type: "required"},
    {Field: "X-Request-Id", Type: "required"},
}

result := validation.ValidateHeaders(req, rules)
if !result.Valid {
    // 处理验证错误
}
ValidateJSONBody 验证 JSON Body
rules := []validation.ValidationRule{
    {Field: "name", Type: "required"},
    {Field: "email", Type: "email"},
    {Field: "age", Type: "number", Min: floatPtr(18), Max: floatPtr(100)},
}

body := []byte(`{"name":"test","email":"test@example.com","age":25}`)
result := validation.ValidateJSONBody(body, rules)
if !result.Valid {
    // 处理验证错误
}

使用示例

HTTP 处理器中的验证
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
    // 验证请求头
    headerRules := []validation.ValidationRule{
        {Field: "Content-Type", Type: "required"},
        {Field: "X-Request-Id", Type: "required"},
    }
    
    headerResult := validation.ValidateHeaders(r, headerRules)
    if !headerResult.Valid {
        http.Error(w, fmt.Sprintf("Header validation failed: %v", headerResult.Errors), http.StatusBadRequest)
        return
    }
    
    // 读取并验证 body
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read request body", http.StatusBadRequest)
        return
    }
    
    bodyRules := []validation.ValidationRule{
        {Field: "name", Type: "required", Message: "Name is required"},
        {Field: "email", Type: "email", Message: "Valid email is required"},
        {Field: "age", Type: "number", Min: floatPtr(18), Max: floatPtr(100)},
    }
    
    bodyResult := validation.ValidateJSONBody(body, bodyRules)
    if !bodyResult.Valid {
        http.Error(w, fmt.Sprintf("Body validation failed: %v", bodyResult.Errors), http.StatusBadRequest)
        return
    }
    
    // 处理创建用户逻辑
}
中间件集成
func ValidationMiddleware(rules []validation.ValidationRule) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            result := validation.ValidateQuery(r, rules)
            if !result.Valid {
                http.Error(w, fmt.Sprintf("Validation failed: %v", result.Errors), http.StatusBadRequest)
                return
            }
            next.ServeHTTP(w, r)
        })
    }
}

// 使用中间件
rules := []validation.ValidationRule{
    {Field: "page", Type: "required"},
    {Field: "size", Type: "number", Min: floatPtr(1), Max: floatPtr(100)},
}

handler := ValidationMiddleware(rules)(myHandler)
自定义错误消息
rule := validation.ValidationRule{
    Field:   "email",
    Type:    "email",
    Message: "请输入有效的邮箱地址",
}
快速失败模式
config := validation.ValidationConfig{
    Source: "query",
    Rules: []validation.ValidationRule{
        {Field: "name", Type: "required"},
        {Field: "email", Type: "email"},
        {Field: "age", Type: "number"},
    },
    FailFast: true, // 遇到第一个错误就停止验证
}

最佳实践

1. 使用声明式验证规则
// ✅ 推荐:声明式规则配置
rules := []validation.ValidationRule{
    {Field: "name", Type: "required"},
    {Field: "email", Type: "email"},
    {Field: "age", Type: "number", Min: floatPtr(18)},
}

// ⚠️ 不推荐:硬编码验证逻辑
if name == "" {
    return errors.New("name is required")
}
if !isValidEmail(email) {
    return errors.New("invalid email")
}
2. 使用自定义错误消息
// ✅ 推荐:友好的错误消息
rules := []validation.ValidationRule{
    {Field: "email", Type: "email", Message: "请输入有效的邮箱地址"},
    {Field: "password", Type: "length", MinLength: intPtr(8), Message: "密码长度至少8位"},
}

// ⚠️ 不推荐:默认错误消息
rules := []validation.ValidationRule{
    {Field: "email", Type: "email"},
    {Field: "password", Type: "length", MinLength: intPtr(8)},
}
3. 复用验证器提升性能
// ✅ 推荐:创建可复用的验证器
var userValidator *validation.RequestValidator

func init() {
    config := validation.ValidationConfig{
        Source: "body",
        Rules: []validation.ValidationRule{
            {Field: "name", Type: "required"},
            {Field: "email", Type: "email"},
        },
    }
    userValidator, _ = validation.NewRequestValidator(config)
}

func handler(w http.ResponseWriter, r *http.Request) {
    result := userValidator.Validate(r)
    // ...
}

// ⚠️ 不推荐:每次请求都创建新验证器
func handler(w http.ResponseWriter, r *http.Request) {
    validator, _ := validation.NewRequestValidator(config)
    result := validator.Validate(r)
}
4. 根据场景选择验证模式
// ✅ 推荐:快速失败适用于严格验证
config := validation.ValidationConfig{
    FailFast: true, // 第一个错误就停止
}

// ✅ 推荐:收集所有错误适用于表单验证
config := validation.ValidationConfig{
    FailFast: false, // 收集所有错误
}
5. 与 Web 框架集成
// ✅ 推荐:使用中间件统一验证
router.Use(ValidationMiddleware([]validation.ValidationRule{
    {Field: "X-Api-Key", Type: "required"},
}))

// ⚠️ 不推荐:每个处理器重复验证逻辑
func handler1(w http.ResponseWriter, r *http.Request) {
    // 重复验证代码
}

func handler2(w http.ResponseWriter, r *http.Request) {
    // 重复验证代码
}
6. 注意事项
  • 空值处理: 除 required 类型外,其他验证类型在值为空时会跳过验证
  • 正则表达式: 建议在创建验证器时预编译正则表达式,提高性能
  • JSON Body: ValidateJSONBody 会自动处理 JSON 中的数字类型(float64)
  • 线程安全: RequestValidator 创建后是只读的,可以安全地在多个 goroutine 中使用
  • 自定义消息: 使用 Message 字段可以提供更友好的错误提示

Documentation

Overview

Package validation 提供参数校验功能,用于 enhance 框架。

Package validation 提供参数校验功能,用于 enhance 框架。

该模块提供字段级校验、跨字段校验、校验规则注册等功能,支持 HTTP 中间件集成。 参考 Jakarta Bean Validation (JSR 380) 的设计理念。

架构设计

  • Validator: 校验器接口,定义校验操作
  • ValidationRule: 校验规则接口,定义单个校验逻辑
  • ValidationContext: 校验上下文,包含被校验对象和错误信息
  • ValidationBuilder: 校验构建器,支持链式配置
  • ValidationMiddleware: HTTP 校验中间件
  • CustomValidator: 自定义验证器接口
  • ValidatorRegistry: 验证器注册表,支持并发安全地注册和获取自定义验证器
  • MiddlewareValidator: 中间件验证器接口

核心功能

  • 字段级校验: 支持 @Required, @Min, @Max, @Email 等常用校验
  • 跨字段校验: 支持比较两个字段的值(如密码确认)
  • 规则注册: 支持自定义校验规则
  • 错误收集: 收集所有校验错误并返回
  • HTTP 集成: 提供 HTTP 中间件自动校验请求参数

使用方式

定义校验规则:

type User struct {
    Name  string `validate:"required,min=2,max=50"`
    Email string `validate:"required,email"`
    Age   int    `validate:"required,min=18,max=100"`
}

校验对象:

validator := validation.NewValidator()
errs := validator.Validate(user)
if len(errs) > 0 {
    // 处理校验错误
}

使用校验构建器:

builder := validation.NewBuilder()
builder.Rule("name").Required().Min(2).Max(50)
builder.Rule("email").Required().Email()
validator := builder.Build()

内置校验规则

  • Required: 必填
  • NotBlank: 非空字符串
  • Min/Max: 最小/最大值
  • Size: 字符串长度或集合大小
  • Email: 邮箱格式
  • URL: URL 格式
  • Regex: 正则表达式匹配
  • In: 值在指定列表中
  • NotIn: 值不在指定列表中

Package validation 提供参数校验功能,用于 enhance 框架。

Package validation 提供参数校验功能,用于 enhance 框架。

Package validation 提供参数校验功能,用于 enhance 框架。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindAndValidate

func BindAndValidate(req *http.Request, obj any) error

BindAndValidate 用于绑定和验证的便捷函数,自动创建绑定器并执行绑定和验证

func DefaultErrorHandler

func DefaultErrorHandler(c any, err error)

DefaultErrorHandler 默认错误处理器。

支持多种上下文类型的错误处理:

  1. http.ResponseWriter: 设置 400 状态码并写入 JSON 错误响应
  2. ResponseWriter (自定义接口): 统一错误响应
  3. 其他类型: 仅记录错误信息,不做响应处理

func Validate

func Validate(value any, rules string) error

Validate 验证单个值是否符合规则。

func ValidateStruct

func ValidateStruct(obj any) error

ValidateStruct 用于验证结构体的便捷函数。

Types

type Binder

type Binder interface {
	// Bind 将请求参数绑定到目标对象。
	Bind(req *http.Request, obj any) error
}

Binder 参数绑定接口。

定义了将 HTTP 请求参数绑定到结构体的标准方法。

type CustomValidator

type CustomValidator interface {
	// Validate 验证字段值。
	Validate(field reflect.Value, param string) (bool, string)
}

CustomValidator 自定义验证器接口。

type DefaultBinder

type DefaultBinder struct {
	Validator Validator // 验证器实例
}

DefaultBinder 默认绑定器,支持从JSON、表单和查询参数绑定数据

func NewDefaultBinder

func NewDefaultBinder(validator Validator) *DefaultBinder

NewDefaultBinder 创建默认绑定器实例

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(req *http.Request, obj any) error

Bind 将请求参数绑定到目标对象,根据请求的内容类型选择适当的绑定方式

type ErrorResponse

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

ErrorResponse 错误响应结构。

用于 HTTP 中间件中的错误响应格式。

func (*ErrorResponse) ToJSON

func (e *ErrorResponse) ToJSON() ([]byte, error)

ToJSON 将错误响应序列化为 JSON 字节。

type FormBinder

type FormBinder struct {
	Validator Validator
}

FormBinder 专门用于表单绑定的绑定器

func NewFormBinder

func NewFormBinder(validator Validator) *FormBinder

NewFormBinder 创建表单绑定器实例

func (*FormBinder) BindForm

func (f *FormBinder) BindForm(req *http.Request, obj any) error

BindForm 仅从表单数据绑定

type GroupRule

type GroupRule struct {
	GroupName string
	Rules     []string
	Inherited bool
}

GroupRule 验证组规则。

type GroupedTagValidator

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

GroupedTagValidator 支持验证组的标签验证器。

func NewGroupedValidator

func NewGroupedValidator(registry *ValidatorRegistry) *GroupedTagValidator

NewGroupedValidator 创建新的分组验证器。

func (*GroupedTagValidator) GetGroup

func (v *GroupedTagValidator) GetGroup(name string) (bool, bool)

GetGroup 获取组是否存在。

func (*GroupedTagValidator) RegisterGroup added in v0.0.3

func (v *GroupedTagValidator) RegisterGroup(name string)

RegisterGroup 注册一个验证组。

func (*GroupedTagValidator) SetDefaultGroups

func (v *GroupedTagValidator) SetDefaultGroups(groups ...string)

SetDefaultGroups 设置默认验证组。

func (*GroupedTagValidator) Validate

func (v *GroupedTagValidator) Validate(obj any) error

Validate 使用默认组验证对象。

func (*GroupedTagValidator) ValidateWithGroups

func (v *GroupedTagValidator) ValidateWithGroups(obj any, groups ...string) error

ValidateWithGroups 使用指定组验证对象。

type JSONBinder

type JSONBinder struct {
	Validator Validator
}

JSONBinder 专门用于JSON绑定的绑定器

func NewJSONBinder

func NewJSONBinder(validator Validator) *JSONBinder

NewJSONBinder 创建JSON绑定器实例

func (*JSONBinder) BindJSON

func (j *JSONBinder) BindJSON(req *http.Request, obj any) error

BindJSON 仅从JSON请求体绑定数据

type MiddlewareConfig

type MiddlewareConfig struct {
	Validator    Validator
	Groups       []string
	ErrorHandler func(c any, err error)
	SkipPaths    []string
}

MiddlewareConfig 中间件配置。

type MiddlewareValidator

type MiddlewareValidator interface {
	// ValidateRequest 验证请求对象。
	ValidateRequest(c any, obj any) error

	// HandleValidationError 处理验证错误。
	HandleValidationError(c any, err error)
}

MiddlewareValidator 中间件验证器接口。

type QueryBinder

type QueryBinder struct {
	Validator Validator
}

QueryBinder 专门用于查询参数绑定的绑定器

func NewQueryBinder

func NewQueryBinder(validator Validator) *QueryBinder

NewQueryBinder 创建查询参数绑定器实例

func (*QueryBinder) BindQuery

func (q *QueryBinder) BindQuery(req *http.Request, obj any) error

BindQuery 仅从查询参数绑定

type RegexCache

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

RegexCache 正则表达式缓存。

func GetRegexCache

func GetRegexCache() *RegexCache

GetRegexCache 获取全局正则表达式缓存。

func NewRegexCache

func NewRegexCache() *RegexCache

NewRegexCache 创建正则表达式缓存。

func (*RegexCache) Clear

func (c *RegexCache) Clear()

Clear 清空缓存。

func (*RegexCache) Get

func (c *RegexCache) Get(pattern string) (*regexp.Regexp, error)

Get 获取或编译正则表达式。

func (*RegexCache) MustGet

func (c *RegexCache) MustGet(pattern string) *regexp.Regexp

MustGet 获取或编译正则表达式,失败则panic。

func (*RegexCache) Size

func (c *RegexCache) Size() int

Size 获取缓存大小。

type RequestValidator

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

RequestValidator HTTP 请求验证器。

func NewRequestValidator

func NewRequestValidator(config ValidationConfig) (*RequestValidator, error)

NewRequestValidator 创建请求验证器

func (*RequestValidator) GetConfig

func (v *RequestValidator) GetConfig() ValidationConfig

GetConfig 获取验证配置。

func (*RequestValidator) Validate

Validate 验证请求。

type ResponseWriter added in v0.0.4

type ResponseWriter interface {
	// SetStatusCode 设置 HTTP 状态码。
	SetStatusCode(code int)
	// SetHeader 设置响应头。
	SetHeader(key, value string)
	// Write 写入响应体。
	Write(data []byte) error
}

ResponseWriter 响应写入器接口。

抽象层,适配不同 HTTP 框架的响应写入。

type RuleBuilder

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

RuleBuilder 验证规则构建器。

支持链式配置校验规则。

func NewRuleBuilder

func NewRuleBuilder() *RuleBuilder

NewRuleBuilder 创建规则构建器。

func (*RuleBuilder) Build

func (b *RuleBuilder) Build() string

Build 构建验证规则字符串。

func (*RuleBuilder) BuildWithMessages

func (b *RuleBuilder) BuildWithMessages() (string, map[string]string)

BuildWithMessages 构建验证规则并返回消息映射。

func (*RuleBuilder) CustomMessage

func (b *RuleBuilder) CustomMessage(message string) *RuleBuilder

CustomMessage 设置自定义错误消息。

func (*RuleBuilder) Email

func (b *RuleBuilder) Email() *RuleBuilder

Email 添加邮箱格式验证。

func (*RuleBuilder) Gt

func (b *RuleBuilder) Gt(n int) *RuleBuilder

Gt 添加大于验证。

func (*RuleBuilder) Gte

func (b *RuleBuilder) Gte(n int) *RuleBuilder

Gte 添加大于等于验证。

func (*RuleBuilder) IP

func (b *RuleBuilder) IP() *RuleBuilder

IP 添加IP地址验证。

func (*RuleBuilder) Len

func (b *RuleBuilder) Len(n int) *RuleBuilder

Len 添加固定长度验证。

func (*RuleBuilder) Lt

func (b *RuleBuilder) Lt(n int) *RuleBuilder

Lt 添加小于验证。

func (*RuleBuilder) Lte

func (b *RuleBuilder) Lte(n int) *RuleBuilder

Lte 添加小于等于验证。

func (*RuleBuilder) Max

func (b *RuleBuilder) Max(n int) *RuleBuilder

Max 添加最大值/长度验证。

func (*RuleBuilder) Min

func (b *RuleBuilder) Min(n int) *RuleBuilder

Min 添加最小值/长度验证。

func (*RuleBuilder) OneOf

func (b *RuleBuilder) OneOf(options ...string) *RuleBuilder

OneOf 添加枚举值验证。

func (*RuleBuilder) Regexp

func (b *RuleBuilder) Regexp(pattern string) *RuleBuilder

Regexp 添加正则表达式验证。

func (*RuleBuilder) Required

func (b *RuleBuilder) Required() *RuleBuilder

Required 添加必填验证。

func (*RuleBuilder) URL

func (b *RuleBuilder) URL() *RuleBuilder

URL 添加URL格式验证。

type RuleValidationError

type RuleValidationError struct {
	// Field 字段名称
	Field string `json:"field"`

	// Message 错误消息
	Message string `json:"message"`

	// Type 错误类型
	Type string `json:"type"`
}

RuleValidationError 验证错误。

type RuleValidationResult

type RuleValidationResult struct {
	// Valid 是否通过验证
	Valid bool `json:"valid"`

	// Errors 错误列表
	Errors []RuleValidationError `json:"errors,omitempty"`
}

RuleValidationResult 验证结果。

func ValidateHeaders

func ValidateHeaders(req *http.Request, rules []ValidationRule) *RuleValidationResult

ValidateHeaders 快速验证请求头。

func ValidateJSONBody

func ValidateJSONBody(body []byte, rules []ValidationRule) *RuleValidationResult

ValidateJSONBody 验证 JSON body。

func ValidateQuery

func ValidateQuery(req *http.Request, rules []ValidationRule) *RuleValidationResult

ValidateQuery 快速验证查询参数。

type TagValidator

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

TagValidator 基于标签的验证器。

支持多种验证规则,通过结构体标签定义校验规则。

func NewTagValidator

func NewTagValidator() *TagValidator

NewTagValidator 创建新的标签验证器实例

func NewTagValidatorWithRegistry

func NewTagValidatorWithRegistry(registry *ValidatorRegistry) *TagValidator

NewTagValidatorWithRegistry 创建带有注册表的标签验证器实例

func (*TagValidator) Validate

func (v *TagValidator) Validate(obj any) error

Validate 验证对象,对结构体的字段进行验证

type ValidateMiddleware

type ValidateMiddleware func(c any, obj any, config *MiddlewareConfig) error

ValidateMiddleware 通用验证中间件函数类型。

func NewValidateMiddleware

func NewValidateMiddleware(config *MiddlewareConfig) ValidateMiddleware

NewValidateMiddleware 创建新的验证中间件。

type ValidationConfig

type ValidationConfig struct {
	// Rules 验证规则
	Rules []ValidationRule `json:"rules"`

	// Source 验证来源:query, header, body
	Source string `json:"source"`

	// FailFast 快速失败(遇到第一个错误就停止)
	FailFast bool `json:"fail_fast"`
}

ValidationConfig 验证配置。

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`           // 字段名称
	Message string `json:"message"`         // 错误消息
	Value   any    `json:"value,omitempty"` // 实际值
}

ValidationError 验证错误结构。

包含字段名称、错误消息和实际值。

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors 验证错误集合。

实现了错误接口,包含多个验证错误。

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

type ValidationRule

type ValidationRule struct {
	// Field 字段名称
	Field string `json:"field"`

	// Type 验证类型:required, string, number, email, regex, enum, min, max, length
	Type string `json:"type"`

	// Value 验证值(用于 enum, regex 等)
	Value string `json:"value,omitempty"`

	// Min 最小值
	Min *float64 `json:"min,omitempty"`

	// Max 最大值
	Max *float64 `json:"max,omitempty"`

	// MinLength 最小长度
	MinLength *int `json:"min_length,omitempty"`

	// MaxLength 最大长度
	MaxLength *int `json:"max_length,omitempty"`

	// Pattern 正则表达式
	Pattern string `json:"pattern,omitempty"`

	// Message 自定义错误消息
	Message string `json:"message,omitempty"`

	// In 枚举值
	In []string `json:"in,omitempty"`
}

ValidationRule 验证规则。

func (ValidationRule) MessageOrDefault

func (r ValidationRule) MessageOrDefault(format string, args ...any) string

MessageOrDefault 获取自定义消息或默认消息。

type Validator

type Validator interface {
	// Validate 验证对象。
	Validate(obj any) error
}

Validator 验证器接口。

定义了验证操作的标准接口。

type ValidatorChain

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

ValidatorChain 验证器链,支持多个对象连续验证。

func NewValidatorChain

func NewValidatorChain() *ValidatorChain

NewValidatorChain 创建验证器链。

func (*ValidatorChain) Add

Add 添加验证器。

func (*ValidatorChain) AddStruct

func (c *ValidatorChain) AddStruct(obj any) *ValidatorChain

AddStruct 添加结构体验证器。

func (*ValidatorChain) AddValue

func (c *ValidatorChain) AddValue(value any, rules string) *ValidatorChain

AddValue 添加值验证器。

func (*ValidatorChain) StopOnFirstError

func (c *ValidatorChain) StopOnFirstError() *ValidatorChain

StopOnFirstError 设置遇到第一个错误时停止。

func (*ValidatorChain) Validate

func (c *ValidatorChain) Validate() error

Validate 执行验证链。

type ValidatorRegistry

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

ValidatorRegistry 验证器注册表。

支持并发安全地注册和获取自定义验证器。 使用 sync.Map 优化读多写少场景的并发性能。

func NewValidatorRegistry

func NewValidatorRegistry() *ValidatorRegistry

NewValidatorRegistry 创建新的验证器注册表。

func (*ValidatorRegistry) Get

func (r *ValidatorRegistry) Get(name string) (CustomValidator, bool)

Get 获取结构体验证器。

func (*ValidatorRegistry) GetFunc

func (r *ValidatorRegistry) GetFunc(name string) (func(reflect.Value, string) (bool, string), bool)

GetFunc 获取函数式验证器。

func (*ValidatorRegistry) Register

func (r *ValidatorRegistry) Register(name string, validator CustomValidator)

Register 注册结构体验证器。

func (*ValidatorRegistry) RegisterFunc

func (r *ValidatorRegistry) RegisterFunc(name string, validator func(reflect.Value, string) (bool, string))

RegisterFunc 注册函数式验证器。

func (*ValidatorRegistry) Unregister

func (r *ValidatorRegistry) Unregister(name string)

Unregister 注销验证器。

Jump to

Keyboard shortcuts

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