Go语言参数校验(go-playground / validator)——自定义校验(自定义验证规则)

go-playground / validator提供了以下校验:

Tag Description
eqcsfield Field Equals Another Field (relative)
eqfield Field Equals Another Field
fieldcontains NOT DOCUMENTED IN doc.go
fieldexcludes NOT DOCUMENTED IN doc.go
gtcsfield Field Greater Than Another Relative Field
gtecsfield Field Greater Than or Equal To Another Relative Field
gtefield Field Greater Than or Equal To Another Field
gtfield Field Greater Than Another Field
ltcsfield Less Than Another Relative Field
ltecsfield Less Than or Equal To Another Relative Field
ltefield Less Than or Equal To Another Field
ltfield Less Than Another Field
necsfield Field Does Not Equal Another Field (relative)
nefield Field Does Not Equal Another Field
Network:
Tag Description
cidr Classless Inter-Domain Routing CIDR
cidrv4 Classless Inter-Domain Routing CIDRv4
cidrv6 Classless Inter-Domain Routing CIDRv6
datauri Data URL
fqdn Full Qualified Domain Name (FQDN)
hostname Hostname RFC 952
hostname_port HostPort
hostname_rfc1123 Hostname RFC 1123
ip Internet Protocol Address IP
ip4_addr Internet Protocol Address IPv4
ip6_addr Internet Protocol Address IPv6
ip_addr Internet Protocol Address IP
ipv4 Internet Protocol Address IPv4
ipv6 Internet Protocol Address IPv6
mac Media Access Control Address MAC
tcp4_addr Transmission Control Protocol Address TCPv4
tcp6_addr Transmission Control Protocol Address TCPv6
tcp_addr Transmission Control Protocol Address TCP
udp4_addr User Datagram Protocol Address UDPv4
udp6_addr User Datagram Protocol Address UDPv6
udp_addr User Datagram Protocol Address UDP
unix_addr Unix domain socket end point Address
uri URI String
url URL String
url_encoded URL Encoded
urn_rfc2141 Urn RFC 2141 String
Strings:
Tag Description
alpha Alpha Only
alphanum Alphanumeric
alphanumunicode Alphanumeric Unicode
alphaunicode Alpha Unicode
ascii ASCII
contains Contains
containsany Contains Any
containsrune Contains Rune
lowercase Lowercase
multibyte Multi-Byte Characters
number NOT DOCUMENTED IN doc.go
numeric Numeric
printascii Printable ASCII
startswith Starts With
uppercase Uppercase
Format:
Tag Description
base64 Base64 String
base64url Base64URL String
btc_addr Bitcoin Address
btc_addr_bech32 Bitcoin Bech32 Address (segwit)
datetime Datetime
email E-mail String
eth_addr Ethereum Address
hexadecimal Hexadecimal String
hexcolor Hexcolor String
hsl HSL String
hsla HSLA String
html HTML Tags
html_encoded HTML Encoded
isbn International Standard Book Number
isbn10 International Standard Book Number 10
isbn13 International Standard Book Number 13
json JSON
latitude Latitude
longitude Longitude
rgb RGB String
rgba RGBA String
ssn Social Security Number SSN
uuid Universally Unique Identifier UUID
uuid3 Universally Unique Identifier UUID v3
uuid3_rfc4122 Universally Unique Identifier UUID v3 RFC4122
uuid4 Universally Unique Identifier UUID v4
uuid4_rfc4122 Universally Unique Identifier UUID v4 RFC4122
uuid5 Universally Unique Identifier UUID v5
uuid5_rfc4122 Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122 Universally Unique Identifier UUID RFC4122
Comparisons:
Tag Description
eq Equals
gt Greater than
gte Greater than or equal
lt Less Than
lte Less Than or Equal
ne Not Equal
除此之前,还可以自定义校验规则,示例代码如下:
package mainimport ( "fmt" "github.com/go-playground/validator" "github.com/satori/go.uuid" "unicode/utf8" )type UserInfo struct { Idstring `validate:"uuid"`//UUID 类型 Name string `validate:"checkName"`//自定义校验 Ageuint8`validate:"min=0,max=130"` //0<=Age<=130 }//自定义校验函数 func checkName(f validator.FieldLevel) bool { // FieldLevel contains all the information and helper functions to validate a field count := utf8.RuneCountInString(f.Field().String()) //通过utf8编码,获取字符串长度 if count >= 2 && count <= 12 { return true } return false } func main() { validate := validator.New() //自定义函数checkName与 struct tag 关联起来 err := validate.RegisterValidation("checkName", checkName) if err!=nil { fmt.Println("注册失败!") return } //UUID引用:satori/go.uuid;添加方法:go get github.com/satori/go.uuid uuid := uuid.Must(uuid.NewV1()) //通过satori/go.uuid,快速生成UUID fmt.Println("UUID:",uuid) user := UserInfo{ Id:uuid.String(), Name: "jiangzhou", Age:223, } err=validate.Struct(user) if err!=nil { for _,e:=range err.(validator.ValidationErrors){ fmt.Println("错误字段:",e.Field()) fmt.Println("错误值:",e.Value()) fmt.Println("错误tag:",e.Tag()) } return } fmt.Println("校验成功") }

运行效果:
【Go语言参数校验(go-playground / validator)——自定义校验(自定义验证规则)】Go语言参数校验(go-playground / validator)——自定义校验(自定义验证规则)
文章图片

    推荐阅读