Documentation
¶
Overview ¶
Package validator 提供零依赖 struct tag 校验和服务网关常用校验能力
Index ¶
- Constants
- func CalculateIDCardChecksum(id string) string
- func ClearRegexCache()
- func ContainsChinese(s string) bool
- func ContainsChineseChars(s string) bool
- func ContainsQuotedNumber(data []byte) bool
- func ConvertNumericStrings(data []byte) ([]byte, error)
- func DerefValue(value any) (any, bool)
- func DetectImageFormat(data []byte) string
- func EmptyToDefault(str, defaultStr string) string
- func FormatSchemaError(result CompareResult) string
- func GetCompiledRegex(pattern string) (*regexp.Regexp, error)
- func GetLocale() string
- func HasDoubleByte(s string) bool
- func HasEmpty(elems []any) (bool, int)
- func HasLocalIP(ip string) bool
- func HasSpecialChars(s string) bool
- func IfNullOrUndefined(str string) bool
- func IsAVIF(data []byte) bool
- func IsAllChinese(str string) (bool, int)
- func IsAllEmpty(elems []any) bool
- func IsAllowedField(field string, allowedFields ...[]string) bool
- func IsAlpha(s string) bool
- func IsAlphanumeric(s string) bool
- func IsBMP(data []byte) bool
- func IsBase64(str string) bool
- func IsBlankString(s string) bool
- func IsCEmpty[T comparable](v T) bool
- func IsChineseIDCard(s string) bool
- func IsChineseIDCardWithChecksum(s string) bool
- func IsChinesePhoneNumber(s string) bool
- func IsDecimalMN(s string, m, n int) bool
- func IsDecimalN(s string, n int) bool
- func IsDigits(s string) bool
- func IsDigitsLengthGeN(s string, n int) bool
- func IsDigitsLengthMN(s string, m, n int) bool
- func IsDigitsLengthN(s string, n int) bool
- func IsDocumentationAddress(ip net.IP) bool
- func IsEmail(email string) bool
- func IsEmptyAfterDeref(value any) (any, bool)
- func IsEmptyLine(s string) bool
- func IsEmptyValue(v reflect.Value) bool
- func IsFilterScalarKind(kind reflect.Kind) bool
- func IsFuncType[T any]() bool
- func IsGIF(data []byte) bool
- func IsGlobalUnicast(ip string) bool
- func IsHEIC(data []byte) bool
- func IsHex(s string) bool
- func IsICO(data []byte) bool
- func IsIP(ip string) bool
- func IsIPAllowed(ip string, cidrList []string) bool
- func IsIPBlocked(ip string, blacklist []string) bool
- func IsIPInRange(ip, start, end net.IP) bool
- func IsImage(data []byte) bool
- func IsImageInFormats(data []byte, formats string) bool
- func IsIntOrFloat(s string) bool
- func IsJPEG(data []byte) bool
- func IsJSONColumnType(dbType string) bool
- func IsJSONNull(data []byte) bool
- func IsLengthN(s string, n int) bool
- func IsLinkLocalIP(ip net.IP) bool
- func IsLowerAlpha(s string) bool
- func IsNegativeNonZeroInt(s string) bool
- func IsNil(x any) bool
- func IsNonZeroLeadingDigits(s string) bool
- func IsNull(str string) bool
- func IsNumStart(c byte) bool
- func IsPNG(data []byte) bool
- func IsPasswordPattern(s string, m, n int) bool
- func IsPositiveNonZeroInt(s string) bool
- func IsPrivateIP(ip string) bool
- func IsSVG(data []byte) bool
- func IsSafeFieldName(field string) bool
- func IsStrongPassword(s string) bool
- func IsTIFF(data []byte) bool
- func IsTimeEmpty(t *time.Time) bool
- func IsTimeFormat(s string) bool
- func IsTimeValid(timeVal any) bool
- func IsTrueString(s string) bool
- func IsUUID(uuid string) bool
- func IsUndefined(str string) bool
- func IsUniqueLocalAddress(ip net.IP) bool
- func IsUpperAlpha(s string) bool
- func IsWebP(data []byte) bool
- func IsWordChars(s string) bool
- func LookupJSONPath(data any, path string) (any, bool)
- func MatchIPInList(ip string, ipList []string) bool
- func MatchIPPattern(ip, pattern string) bool
- func MatchIPWithWildcard(ip, pattern string) bool
- func MatchPathGlob(path, pattern string) bool
- func MatchPathInList(path string, patterns []string) bool
- func NewEnumValidator[T comparable](values ...T) *validate.EnumValidator[T]
- func NormalizeFilterValue(value any) any
- func NormalizeFilterValueIfNotEmpty(value any) (any, bool)
- func NormalizeFilterValueSlice(values []any) []any
- func NormalizeImageFormat(name string) (string, bool)
- func ParseMonth(month string) (time.Month, error)
- func ParseWeek(week string) (time.Weekday, error)
- func RegisterI18n(locale, key, template string)
- func RegisterI18nMessages(locale string, messages map[string]string)
- func RegisterTranslation(locale, tag, template string)
- func RegisterTranslations(locale string, items map[string]string)
- func ScanJSONString(data []byte, start int) (int, error)
- func ScanJSONValueEnd(data []byte, start int) (int, error)
- func SetLocale(locale string)
- func SkipJSONSpaces(data []byte, i int) int
- func UnwrapProtobufEnum(value any) (any, bool)
- func UnwrapProtobufWrapper(value any) (any, bool)
- func ValidateJSON(data []byte) error
- func ValidateJSONWithData(body []byte) (any, error)
- type CompareOperator
- type CompareResult
- func CompareNumbers[T Number](actual, expect T, op CompareOperator) CompareResult
- func CompareStrings(actual, expect string, op CompareOperator) CompareResult
- func ValidateBase64(str string) CompareResult
- func ValidateContains(body []byte, substring string) CompareResult
- func ValidateContentType(headers map[string]string, expected string) CompareResult
- func ValidateEmail(email string) CompareResult
- func ValidateHTTP(urlStr string) CompareResult
- func ValidateHeader(headers map[string]string, key, expected string, op CompareOperator) CompareResult
- func ValidateIP(ipStr string) CompareResult
- func ValidateIPAddress(ipStr string) CompareResult
- func ValidateImage(data []byte) CompareResult
- func ValidateImageInFormats(data []byte, formats string) CompareResult
- func ValidateJSONField(body []byte, field string, expected any) CompareResult
- func ValidateJSONFields(body []byte, rules map[string]any) []CompareResult
- func ValidateJSONPath(body []byte, jsonPath string, expected any, op CompareOperator) CompareResult
- func ValidateJSONPathExists(body []byte, jsonPath string) CompareResult
- func ValidateJSONSchema(data, s any) CompareResult
- func ValidateNotContains(body []byte, substring string) CompareResult
- func ValidateProtocol(urlStr string, allowedProtocols ...string) CompareResult
- func ValidateRegex(body []byte, pattern string) CompareResult
- func ValidateStatusCode(statusCode, expected int, op CompareOperator) CompareResult
- func ValidateStatusCodeRange(actual, min, max int) CompareResult
- func ValidateString(actual, expect string, op CompareOperator) CompareResult
- func ValidateStructWithSchema(structData, s any) CompareResult
- func ValidateUUID(uuidStr string) CompareResult
- func ValidateWebSocket(urlStr string) CompareResult
- type FieldError
- type FieldLevel
- type Func
- type FuncCtx
- type IPBase
- type IPSet
- type InvalidValidationError
- type JSONSchema
- type Number
- type Option
- type SchemaBuilder
- type TagNameFunc
- type Validate
- func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
- func (v *Validate) RegisterValidation(tag string, fn Func, _ ...bool) error
- func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, _ ...bool) error
- func (v *Validate) SetTagName(name string)
- func (v *Validate) Struct(s any) error
- func (v *Validate) StructCtx(ctx context.Context, s any) error
- func (v *Validate) Var(field any, tag string) error
- func (v *Validate) VarCtx(ctx context.Context, field any, tag string) error
- func (v *Validate) VarString(field, tag string) error
- func (v *Validate) VarStringCtx(ctx context.Context, field, tag string) error
- type ValidationErrors
- type ValidationMessage
Constants ¶
const ( OpEqual = constants.OpEqual OpNotEqual = constants.OpNotEqual OpGreaterThan = constants.OpGreaterThan OpGreaterThanOrEqual = constants.OpGreaterThanOrEqual OpLessThan = constants.OpLessThan OpLessThanOrEqual = constants.OpLessThanOrEqual OpContains = constants.OpContains OpNotContains = constants.OpNotContains OpHasPrefix = constants.OpHasPrefix OpHasSuffix = constants.OpHasSuffix OpRegex = constants.OpRegex OpEmpty = constants.OpEmpty OpNotEmpty = constants.OpNotEmpty OpSymbolEqual = constants.OpSymbolEqual OpSymbolNotEqual = constants.OpSymbolNotEqual OpSymbolGreaterThan = constants.OpSymbolGreaterThan OpSymbolGreaterThanOrEqual = constants.OpSymbolGreaterThanOrEqual OpSymbolLessThan = constants.OpSymbolLessThan OpSymbolLessThanOrEqual = constants.OpSymbolLessThanOrEqual )
Variables ¶
This section is empty.
Functions ¶
func CalculateIDCardChecksum ¶
CalculateIDCardChecksum 计算给定17位身份证号的校验和字符
func ContainsChineseChars ¶
ContainsChineseChars 检查字符串是否包含中文字符
func ContainsQuotedNumber ¶
ContainsQuotedNumber 使用零分配字节扫描快速判断 JSON 中是否存在引号包裹的数字
func ConvertNumericStrings ¶
ConvertNumericStrings 递归遍历 JSON 数据,将数字字符串自动转换为 json.Number 类型
func DetectImageFormat ¶
DetectImageFormat 基于魔数嗅探图片格式,返回规范格式名,无法识别时返回空字符串
func EmptyToDefault ¶
EmptyToDefault 在字符串为空时返回默认值
func FormatSchemaError ¶
func FormatSchemaError(result CompareResult) string
FormatSchemaError 提取 schema 校验错误消息
func GetCompiledRegex ¶
GetCompiledRegex 获取编译的正则(带缓存)
func IfNullOrUndefined ¶
IfNullOrUndefined 判断字符串是否为 null 或 undefined
func IsAllChinese ¶
IsAllChinese 检查字符串是否全部由汉字组成,返回是否全为汉字及非汉字字符数
func IsAllowedField ¶
IsAllowedField 判断字段是否在白名单中
func IsChineseIDCard ¶
IsChineseIDCard 检查字符串是否为有效的大陆身份证号(15位或18位格式)
func IsChineseIDCardWithChecksum ¶
IsChineseIDCardWithChecksum 检查18位身份证号(含校验位验证)
func IsChinesePhoneNumber ¶
IsChinesePhoneNumber 检查字符串是否为有效的大陆手机号
func IsDigitsLengthGeN ¶
IsDigitsLengthGeN 检查字符串是否为长度不小于 n 的纯数字
func IsDigitsLengthMN ¶
IsDigitsLengthMN 检查字符串是否为长度在 m 到 n 之间的纯数字
func IsDigitsLengthN ¶
IsDigitsLengthN 检查字符串是否为长度等于 n 的纯数字
func IsDocumentationAddress ¶
IsDocumentationAddress 判断 IP 是否为文档专用地址
func IsEmptyAfterDeref ¶
IsEmptyAfterDeref 解引用后判断值是否为空
func IsFilterScalarKind ¶
IsFilterScalarKind 判断 Kind 是否属于过滤场景下的标量类型(bool/number)
func IsImageInFormats ¶
IsImageInFormats 判断字节内容是否为白名单内的有效图片,白名单为空格分隔的格式名,出现未知格式名时校验失败
func IsJSONColumnType ¶
IsJSONColumnType 判断数据库列类型是否属于 JSON 类型
func IsNegativeNonZeroInt ¶
IsNegativeNonZeroInt 检查字符串是否为负整数(首位非零)
func IsNonZeroLeadingDigits ¶
IsNonZeroLeadingDigits 检查字符串是否为非零开头的纯数字
func IsPasswordPattern ¶
IsPasswordPattern 检查密码是否符合规则(字母开头,字母数字下划线,长度 m~n)
func IsPositiveNonZeroInt ¶
IsPositiveNonZeroInt 检查字符串是否为正整数(可选+前缀,首位非零)
func IsStrongPassword ¶
IsStrongPassword 检查密码强度(8位+大小写+数字+特殊字符)
func IsUniqueLocalAddress ¶
IsUniqueLocalAddress 判断 IP 是否为 IPv6 唯一本地地址(ULA)
func LookupJSONPath ¶
LookupJSONPath 按轻量路径读取 JSON 数据
func MatchIPInList ¶
MatchIPInList 判断 IP 是否命中任意规则
func MatchIPWithWildcard ¶
MatchIPWithWildcard 使用星号通配符匹配 IPv4
func MatchPathGlob ¶
MatchPathGlob Glob 模式匹配路径(支持 * 和 ? 通配符)
func MatchPathInList ¶
MatchPathInList 判断路径是否命中任意路径前缀
func NewEnumValidator ¶
func NewEnumValidator[T comparable](values ...T) *validate.EnumValidator[T]
NewEnumValidator 创建枚举校验器
func NormalizeFilterValueIfNotEmpty ¶
NormalizeFilterValueIfNotEmpty 过滤空值后返回归一化值
func NormalizeFilterValueSlice ¶
NormalizeFilterValueSlice 归一化过滤值切片
func NormalizeImageFormat ¶
NormalizeImageFormat 归一化图片格式名,忽略大小写且 jpg 等价 jpeg,未知格式名返回 false
func RegisterI18n ¶
func RegisterI18n(locale, key, template string)
RegisterI18n 注册或覆盖某个语言下的单个 i18n 消息模板
func RegisterI18nMessages ¶
RegisterI18nMessages 批量注册某个语言下的 i18n 消息模板
func RegisterTranslation ¶
func RegisterTranslation(locale, tag, template string)
RegisterTranslation 注册或覆盖某个语言下的单个规则翻译模板
func RegisterTranslations ¶
RegisterTranslations 批量注册某个语言下的规则翻译模板
func ScanJSONString ¶
ScanJSONString 扫描 JSON 字符串,返回字符串结束后一位的位置
func ScanJSONValueEnd ¶
ScanJSONValueEnd 扫描任意 JSON 值,返回值结束后一位的位置
func UnwrapProtobufEnum ¶
UnwrapProtobufEnum 通过反射解开 protobuf enum,提取底层数值
func UnwrapProtobufWrapper ¶
UnwrapProtobufWrapper 通过反射解开 protobuf wrapper
func ValidateJSONWithData ¶
ValidateJSONWithData 校验 JSON 并返回反序列化数据
Types ¶
type CompareResult ¶
type CompareResult = validate.CompareResult
CompareResult 表示一次比较校验结果
func CompareNumbers ¶
func CompareNumbers[T Number](actual, expect T, op CompareOperator) CompareResult
CompareNumbers 比较两个数值
func CompareStrings ¶
func CompareStrings(actual, expect string, op CompareOperator) CompareResult
CompareStrings 比较两个字符串
func ValidateContains ¶
func ValidateContains(body []byte, substring string) CompareResult
ValidateContains 校验字节内容是否包含子串
func ValidateContentType ¶
func ValidateContentType(headers map[string]string, expected string) CompareResult
ValidateContentType 校验 Content-Type 是否包含期望类型
func ValidateHeader ¶
func ValidateHeader(headers map[string]string, key, expected string, op CompareOperator) CompareResult
ValidateHeader 根据操作符比较 Header 值
func ValidateIPAddress ¶
func ValidateIPAddress(ipStr string) CompareResult
ValidateIPAddress 校验 IP 地址格式
func ValidateImageInFormats ¶
func ValidateImageInFormats(data []byte, formats string) CompareResult
ValidateImageInFormats 校验字节内容是否为白名单内的有效图片
func ValidateJSONField ¶
func ValidateJSONField(body []byte, field string, expected any) CompareResult
ValidateJSONField 校验 JSON 顶层字段是否等于期望值
func ValidateJSONFields ¶
func ValidateJSONFields(body []byte, rules map[string]any) []CompareResult
ValidateJSONFields 批量校验 JSON 顶层字段
func ValidateJSONPath ¶
func ValidateJSONPath(body []byte, jsonPath string, expected any, op CompareOperator) CompareResult
ValidateJSONPath 校验 JSON 路径的值
func ValidateJSONPathExists ¶
func ValidateJSONPathExists(body []byte, jsonPath string) CompareResult
ValidateJSONPathExists 校验 JSON 路径是否存在
func ValidateJSONSchema ¶
func ValidateJSONSchema(data, s any) CompareResult
ValidateJSONSchema 校验数据是否符合 schema
func ValidateNotContains ¶
func ValidateNotContains(body []byte, substring string) CompareResult
ValidateNotContains 校验字节内容是否不包含子串
func ValidateProtocol ¶
func ValidateProtocol(urlStr string, allowedProtocols ...string) CompareResult
ValidateProtocol 校验 URL 协议是否在允许列表中
func ValidateRegex ¶
func ValidateRegex(body []byte, pattern string) CompareResult
ValidateRegex 校验字节内容是否匹配正则表达式
func ValidateStatusCode ¶
func ValidateStatusCode(statusCode, expected int, op CompareOperator) CompareResult
ValidateStatusCode 比较 HTTP 状态码
func ValidateStatusCodeRange ¶
func ValidateStatusCodeRange(actual, min, max int) CompareResult
ValidateStatusCodeRange 校验 HTTP 状态码是否在闭区间内
func ValidateString ¶
func ValidateString(actual, expect string, op CompareOperator) CompareResult
ValidateString 校验字符串关系
func ValidateStructWithSchema ¶
func ValidateStructWithSchema(structData, s any) CompareResult
ValidateStructWithSchema 校验结构体或 map 是否符合 schema
func ValidateWebSocket ¶
func ValidateWebSocket(urlStr string) CompareResult
ValidateWebSocket 校验 WebSocket URL
type FieldError ¶
type FieldError interface {
Tag() string
ActualTag() string
Namespace() string
StructNamespace() string
Field() string
StructField() string
Value() any
Param() string
Kind() reflect.Kind
Type() reflect.Type
Error() string
}
FieldError 表示单个字段校验失败详情
type FieldLevel ¶
type FieldLevel interface {
Top() reflect.Value
Parent() reflect.Value
Field() reflect.Value
FieldName() string
StructFieldName() string
GetTag() string
Param() string
}
FieldLevel 为自定义规则提供当前字段、父结构和标签参数
type FuncCtx ¶
type FuncCtx func(ctx context.Context, fl FieldLevel) bool
FuncCtx 表示带 context 的自定义字段校验函数
type IPSet ¶
IPSet 表示预编译 IP 规则集合
func CompileIPSet ¶
CompileIPSet 将 IP 规则编译为可复用集合
func MustCompileIPSet ¶
MustCompileIPSet 编译 IP 规则,失败时 panic
type InvalidValidationError ¶
InvalidValidationError 表示传入校验器的参数类型不合法
func (*InvalidValidationError) Error ¶
func (e *InvalidValidationError) Error() string
type JSONSchema ¶
type JSONSchema = schema.JSONSchema
JSONSchema 描述 Argus 支持的 JSON Schema 子集
func QuickSchema ¶
func QuickSchema(properties map[string]string, required ...string) JSONSchema
QuickSchema 根据字段类型快速创建对象 schema
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
Number 表示可比较数值类型集合
type Option ¶
type Option func(*Validate)
Option 表示校验器初始化配置项
func WithFailFast ¶
func WithFailFast() Option
WithFailFast 首个错误即停止校验(默认关闭)
默认行为是收集全部字段错误:命中失败后仍继续遍历剩余字段, 因此"首字段失败"与"末字段失败"耗时相同(实测 15 字段结构体 482.9 vs 461.7 ns)。 请求入口的常见诉求是"拒绝这个请求",调用方往往只需首个错误或 err != nil, 此时继续校验剩余字段是纯浪费。
开启后 ValidationErrors 只含首个错误。必须显式开启而非默认—— 依赖"拿到全部错误"(如表单逐字段回显)的调用方不能被静默改掉语义。
func WithPrivateFieldValidation ¶
func WithPrivateFieldValidation() Option
WithPrivateFieldValidation 保留私有字段校验选项,用于平滑迁移 go-playground 调用
func WithRequiredStructEnabled ¶
func WithRequiredStructEnabled() Option
WithRequiredStructEnabled 允许 required 对非指针结构体零值生效
type TagNameFunc ¶
type TagNameFunc func(field reflect.StructField) string
TagNameFunc 用于解析字段展示名,例如从 json tag 中取字段名
type Validate ¶
type Validate struct {
// contains filtered or unexported fields
}
Validate 是可复用且并发安全的校验器实例
func (*Validate) RegisterTagNameFunc ¶
func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
RegisterTagNameFunc 注册字段展示名解析函数
func (*Validate) RegisterValidation ¶
RegisterValidation 注册自定义字段校验函数
func (*Validate) RegisterValidationCtx ¶
RegisterValidationCtx 注册带 context 的自定义字段校验函数
func (*Validate) SetTagName ¶
SetTagName 设置校验标签名,默认使用 validate
type ValidationErrors ¶
type ValidationErrors []FieldError
ValidationErrors 表示字段校验失败集合
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
func (ValidationErrors) MissingFields ¶
func (ve ValidationErrors) MissingFields() []string
MissingFields 返回 required 系列规则中缺失的字段名,字段名优先使用 json tag
func (ValidationErrors) RequiredMessages ¶
func (ve ValidationErrors) RequiredMessages(locale string) []ValidationMessage
RequiredMessages 只返回 required 系列规则产生的缺失字段错误
func (ValidationErrors) Translate ¶
func (ve ValidationErrors) Translate(locale string) []ValidationMessage
Translate 将 ValidationErrors 转换为数组化的 i18n 字段错误
type ValidationMessage ¶
type ValidationMessage struct {
Field string `json:"field"`
Namespace string `json:"namespace"`
StructField string `json:"struct_field,omitempty"`
StructNamespace string `json:"struct_namespace,omitempty"`
Tag string `json:"tag"`
ActualTag string `json:"actual_tag"`
Param string `json:"param,omitempty"`
Value any `json:"value,omitempty"`
Message string `json:"message"`
}
ValidationMessage 表示一个可直接序列化给 HTTP/gRPC 网关的字段错误
func TranslateValidationErrors ¶
func TranslateValidationErrors(err error, locale string) []ValidationMessage
TranslateValidationErrors 将 error 转换为数组化的 i18n 字段错误
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package rule 提供 Argus 的标签规则、跨字段规则和时间表达式能力
|
Package rule 提供 Argus 的标签规则、跨字段规则和时间表达式能力 |
|
Package schema 提供轻量 JSON Schema 子集校验能力
|
Package schema 提供轻量 JSON Schema 子集校验能力 |
|
Package validate 承载从 go-toolbox/pkg/validator 迁移而来的通用校验能力
|
Package validate 承载从 go-toolbox/pkg/validator 迁移而来的通用校验能力 |