validate

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: GPL-3.0 Imports: 19 Imported by: 0

README

Go通用的数据验证与过滤库,使用简单,内置大部分常用验证器、过滤器,支持自定义消息、字段翻译。

  • 简单方便,支持前置验证检查, 支持添加自定义验证器
    • 大多数过滤器和验证器都有别名方便使用
  • 可以在任何框架中使用 validate,例如 Gin、Echo、Chi 等
  • 支持直接使用规则来验证值 例如: (new Validate()).Check([Value{"name", "soudom"}])
  • 完善的单元测试,测试覆盖率 > 90%

单独使用实例方法配置验证

该实例调用3个方法:

  • Lang() 甚至错误消息默认的语言,支持Lang.CN/Lang.EN
  • Rule(r map[string]string{}) 设置验证规则
  • SetRule(name, rule string) 设置单个验证规则
  • Message(m map[string]string) 可以自定义验证器错误消息
  • SetMessage(cases ...string) 设置多个验证错误消息
  • Scene(name string) 该方法只支持自定义结构体嵌入Validate结构体下使用
  • Check(val []Value, group ...string) 验证结果是否符合预期,第二个参数只支持自定义结构体嵌入Validate结构体下使用

代码示例:

验证Map数据

package main

import "fmt"
import "gitee.com/aivi/validate"
import "validate/i18n"

func main()  {
	// 设置默认语言,内置默认为CN,该语句作为演示使用,实际情况下不用写
	i18n.Set(i18n.CN)
	
	// 要验证的数据
	m := []validate.Value{
		{"name", "inhere"},
		{"age", 100},
	}
	
	v := validate.NewValidate()
	// 设置验证规则以及错误提示信息
	res := v.Rule(map[string]string{"name": "require|length:2,14"}).Message(map[string]string{"name.require": "name不能为空", "name.length": "name的值在2-14个字符之间"}).Check(m)
	
	// 单个验证规则设置
	// v.SetRule("nickName", "require|length:2,16|chs")
	// v.SetMessage("nickName.require", "昵称是必须项", "nickName.length", "昵称长度为2-16个字符", "nickName.chs", "昵称只能为汉字")
	// res := v.Check(m)
	
	if res { // validate ok
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
		fmt.Println(v.Errors.One()) // returns a random error message text
	}
}

内置验证器

几大类别:

  • (为空)必填验证
  • 类型验证
  • 大小、长度验证
  • 字段值比较验证
  • 文件验证
  • 日期验证
  • 字符串检查验证
  • 其他验证
验证器 描述信息
required 字段为必填项,值不能为空
int 检查值是 int 类型
bool 检查值是布尔字符串("true", "false").
float 检查值是float32/float64,是其中之一则验证通过.
number 检查值是否为纯数字格式.
array 检查值是否为数组
accepted 验证某个字段是否为 yes, on, 或是 1。这在确认"服务条款"是否同意时很有用
cntrl 验证某个字段是否为换行,缩进,空格
xdigit 验证某个字段是否是十六进制
color 验证某个字段是否是十六进制颜色值,比如:#ffcc22
url 验证值是否为url类型,包括但不限于是(https/http/ws/wss/ftp/tcp/udp)://ip(或者域名):端口
email 验证是否为email格式
mobile 验证是否为手机号
date 验证是否为日期格式,格式为:yyyy-mm-dd,yyyy/mm/dd,mm/dd/yyyy
datetime 验证是否为日期时间格式,日期部分为上一部分的date格式,时间格式为:hh:mm,hh:mm:ss,yymmdd
time 验证是否为时间格式,格式为:hh:mm,hh:mm:ss,yymmdd
zip 验证是否为邮政编码,长度为6为数字
ip 验证是否为ip格式,包括ipv4, ipv6
mac 验证是否为mac地址
idcard 验证是否为身份证号码
chs 验证是否为纯汉字,不包括标点符号
chsAlpha 验证是否为汉字,字母,不包括标点符号
chsAlphaNum 验证是否为汉字,字母,数字,不包括标点符号
chsDash 验证是否为汉字,字母,数字,_,-,不包括标点符号
alpha 验证是否为字母
lower 验证是否为小写字母
upper 验证是否为大写字母
alphaNum 验证是否为字母,数字
dash 验证是否为字母,数字,_,-
en 验证是否为英文,包括但不限于英文大小写,数字,英文标点符号,只要符合要求的80%以上就表示是英文
cn 验证是否为中文,包括但不限于中文,数字,标点符号,只要符合要求的80%以上就表示是中文
length: 验证其长度范围,比如: length:2,16,长度是否是2-16个字符,length:15,长度最多为15个字符
max= 验证值最多是多少,比如: max=15,值最大为15
min= 验证值最小是多少,比如: max=5,值最小为5
in: 验证值是否在此列表中,比如: in:one,two,three,four,值只能是这四个之一
notin: 验证值不在此列表中,比如: notin:one,two,three,four,值不能是这四个值
between 验证值是否在此区间内,比如: between:1,15,值是否是大于等于1且小于等于15
notBetween 验证值是否不在此区间内,比如: notBetween:1,15,值是否小于1或者大于15
prefix= 验证值的前缀,比如: prefix=more,值必须是more开头
suffix= 验证值的后缀,比如: suffix=.com,值必须是.com结尾
eq= 验证值是否和指定的字段的值相等,比如: eq=password,值必须和password字段的值相等
file: 验证是否是文件
image: 验证是否是图片,格式为:image:640,320,auto,10,2或者image:9,16,rate,10,2,参数分别是宽,高,类型,允许的图片大小,误差,其中类型有两种,一种是auto,表示具体的宽高,另一种是rate,表示宽高比,比如16:9。这里的误差是指图片的宽高比与目标图片的宽高比,这两者的相差的绝对值最多为多少。
fileExt: 验证值是否是允许的扩展名,比如:fileExt:.png,.jpg,.jpeg,.gif,.webp
fileMime: 验证值是否是允许的类型,比如:fileMime:image/jpeg,image/png,application/pdf
fileSize: 验证值是否超过允许的文件大小,单位是MB,比如:10,表示最大允许10MB

Documentation

Index

Constants

View Source
const (
	MaxUint32 = ^uint32(0)
	MinUint32 = 0
	MaxInt32  = int32(MaxUint32 >> 1)
	MinInt32  = -MaxInt32 - 1
	MaxUint64 = ^uint64(0)
	MinUint64 = 0
	MaxInt64  = int64(MaxUint64 >> 1)
	MinInt64  = -MaxInt64 - 1
)

Variables

This section is empty.

Functions

func All

func All(cases ...bool) bool

All 所有的都为true,就返回true,否则就为false

func Any

func Any(cases ...bool) bool

Any 只要有一个条件为true,那么就返回为true,否则为false

func If

func If[T any](condition bool, trueVal T) T

If 运算符

func IfElse

func IfElse[T any](condition bool, trueVal, falseVal T) T

IfElse 三元运算符

func IfFor

func IfFor[T any](arr []T, condition func(m T) bool, safe ...bool) []T

IfFor 实现python中的 (n for n in ses if n % 2 == 0)

func IfLazy

func IfLazy[T any](condition bool, trueFn, falseFn func() T) T

IfLazy if懒惰三元运算符

func InArray

func InArray[T comparable](ele T, arr []T) bool

InArray 元素是否在数组中

func IsAlpha

func IsAlpha(val string) bool

IsAlpha 是否是字母

func IsAlphaDash

func IsAlphaDash(val string) bool

IsAlphaDash 是否是字母,数字, -, _

func IsAlphaNum

func IsAlphaNum(val string) bool

IsAlphaNum 是否是字母,数字

func IsArray

func IsArray(t any) bool

IsArray 是否为数组

func IsBool

func IsBool(val any) bool

IsBool 是否是布尔

func IsCard

func IsCard(val string) bool

IsCard 身份证校验

func IsChinese

func IsChinese(val string) bool

IsChinese 是否是中文,包含中英文标点,数字

func IsChs

func IsChs(val string) bool

IsChs 是否是汉字

func IsChsAlpha

func IsChsAlpha(val string) bool

IsChsAlpha 是否是汉字,字母

func IsChsAlphaNum

func IsChsAlphaNum(val string) bool

IsChsAlphaNum 是否是汉字,字母,数字

func IsChsDash

func IsChsDash(val string) bool

IsChsDash 是否是汉字,字母,数字,-,_

func IsColor

func IsColor(s string) bool

func IsDate

func IsDate(val string) bool

IsDate 日期校验

func IsDateTime

func IsDateTime(val string) bool

IsDateTime 日期时间校验

func IsEmail

func IsEmail(val string) bool

IsEmail 是否是合法的Email

func IsEmpty

func IsEmpty(val any) bool

IsEmpty 是否为空

func IsEnglish

func IsEnglish(val string) bool

IsEnglish 是否是英文,这里是英文占据整个字符串的80%以上,就可以看作是英文

func IsFile

func IsFile(req *http.Request, maxSize int, allowExt []string, allowMime []string) bool

IsFile 是否是文件

func IsImage

func IsImage(req *http.Request, fieldName string, width, heigh, maxSize int, diff float64, typ ...string) error

IsImage 是否是图片文件

func IsInt

func IsInt(val any) bool

IsInt 是否是整数

func IsIp

func IsIp(val string) bool

IsIp 是否是IP格式,包括IPv4,Ipv6

func IsLower

func IsLower(val string) bool

IsLower 是否是小写字母

func IsMac

func IsMac(val string) bool

IsMac 是否是mac地址

func IsMobile

func IsMobile(val string) bool

IsMobile 检测是否是手机号

func IsNumber

func IsNumber(val string) bool

IsNumber 是否是纯数字,不包含".","+","-","E","e等数学符号

func IsReal

func IsReal(val any) bool

IsReal 是否是小数

func IsTime

func IsTime(val string) bool

IsTime 时间校验

func IsUpper

func IsUpper(val string) bool

IsUpper 是否是大写字母

func IsUrl

func IsUrl(val string) bool

IsUrl 是否是URL格式 ^[http|https|wss|ws|ftp|tcp|upd]+$

func IsXdigit

func IsXdigit(t string) bool

IsXdigit 是否为16进制

func IsZip

func IsZip(val string) bool

IsZip 检测是否是邮政编码

func Match

func Match[T any](cases ...any) T

Match 匹配运算符

func ParseInt

func ParseInt(val string) (res int)

ParseInt 字符串转整型

func ToDouble

func ToDouble(v any) (float64, bool)

ToDouble 任意基础类型转换为float64

func ToFloat

func ToFloat(v any) float32

ToFloat 任意基础类型转换为float64

func ToInt

func ToInt(v any) (int, bool)

ToInt 任意类型转换为int

func ToInt64

func ToInt64(v any) int64

ToInt64 任意类型转换为int64

func ToUint

func ToUint(v any) (uint, bool)

ToUint 任意类型转换为uint

func ToUint64

func ToUint64(v any) (uint64, bool)

ToUint64 任意类型转换为uint64

Types

type MapStr

type MapStr map[string]string

func (MapStr) Get

func (a MapStr) Get(key string) string

func (MapStr) GetEqContent

func (ms MapStr) GetEqContent() (res []string)

GetEqContent 获取map中的值包含eq=后面的字段,比如 eq=password,得到password

type Validate

type Validate struct {
	Rules        MapStr
	Messages     MapStr
	Groups       map[string]MapStr
	Scenes       map[string][]string
	CurrentScene string
	// contains filtered or unexported fields
}

func (*Validate) Check

func (v *Validate) Check(data []Value, group ...string) error

func (*Validate) Lang

func (v *Validate) Lang(l i18n.Lang) *Validate

func (*Validate) Message

func (v *Validate) Message(m MapStr) *Validate

func (*Validate) Rule

func (v *Validate) Rule(r MapStr) *Validate

func (*Validate) Scene

func (v *Validate) Scene(name string) *Validate

Scene 验证场景仅针对结构体内嵌验证器有效,独立验证不存在验证场景的概念

func (*Validate) SetMessage

func (v *Validate) SetMessage(cases ...string) *Validate

func (*Validate) SetRule

func (v *Validate) SetRule(name string, rule string) *Validate

type Validater

type Validater[T any] interface {
	Check(data []Value, group ...string) error
	Rule(r MapStr) *T
	SetRule(name string, rule string) *T
	Message(m MapStr) *T
	SetMessage(cases ...string) *T
	Scene(name string) *T
	Lang(lang i18n.Lang) *T
}

func NewValidate

func NewValidate() Validater[Validate]

type Value

type Value struct {
	Key string
	Val any
}

Value 要验证的内容

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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