“Golang go-playground validator 包中文教程”的版本间差异
本页内容
(创建页面,内容为“25 在Web开发中经常会对用户输入数据进行校验,或者在提供API给第三方使用时候需要对字段进行校验,防止脏数据和恶意请求。 Golang官方维护了 '''go-playground/validator'''<ref>https://github.com/go-playground/validator</ref> 是使用最广泛的包,自带了非常多常用的校验规则。其基于标签实现结构和单个字段的值验证。 == 特性 == * 使用验证标签…”) |
(→验证规则) |
||
第129行: | 第129行: | ||
== 验证规则 == | == 验证规则 == | ||
=== 字段验证规则 === | |||
{| class="wikitable" | |||
|- | |||
! 标签 | |||
! 说明 | |||
|- | |||
| eqcsfield | |||
| 字段等于另一个字段(相对) | |||
|- | |||
| eqfield | |||
| 字段等于另一个字段 | |||
|- | |||
| fieldcontains | |||
| 字段包含 | |||
|- | |||
| fieldexcludes | |||
| 字段不包含 | |||
|- | |||
| 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 | |||
|} |
2022年9月27日 (二) 20:16的版本
在Web开发中经常会对用户输入数据进行校验,或者在提供API给第三方使用时候需要对字段进行校验,防止脏数据和恶意请求。 Golang官方维护了 go-playground/validator[1] 是使用最广泛的包,自带了非常多常用的校验规则。其基于标签实现结构和单个字段的值验证。
特性
- 使用验证标签或自定义验证器进行跨字段和跨结构验证。
- slice、array 和 map 层级校验支持,允许验证多维字段的任何或所有级别。
- 支持对 map key 和 value 以进行验证
- 支持处理自定义字段类型,例如 sql driver
- 重命名验证标签,允许将多个验证映射到单个标签,以便更轻松地定义struct上的验证规则
- 支持提取验证数据字段的名称,例如可以指定在验证时提取 JSON 名称,并使其在生成的 FieldError 中可用
- 可设置的 i18n 错误消息。
- gin web 框架的默认验证器
安装
示例
go get github.com/go-playground/validator/v10
代码中引入包
import "github.com/go-playground/validator/v10"
简单的用法示例[2]
可以看出我们只用在结构体的字段上加上对应的`validate:"xx"`即可添加对应验证规则。
示例
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
// User contains user information
type User struct {
FirstName string `validate:"required"`
LastName string `validate:"required"`
Age uint8 `validate:"gte=0,lte=130"`
Email string `validate:"required,email"`
FavouriteColor string `validate:"iscolor"` // alias for 'hexcolor|rgb|rgba|hsl|hsla'
Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage...
}
// Address houses a users address information
type Address struct {
Street string `validate:"required"`
City string `validate:"required"`
Planet string `validate:"required"`
Phone string `validate:"required"`
}
// use a single instance of Validate, it caches struct info
var validate *validator.Validate
func main() {
validate = validator.New()
validateStruct()
validateVariable()
}
func validateStruct() {
address := &Address{
Street: "Eavesdown Docks",
Planet: "Persphone",
Phone: "none",
}
user := &User{
FirstName: "Badger",
LastName: "Smith",
Age: 135,
Email: "[email protected]",
FavouriteColor: "#000-",
Addresses: []*Address{address},
}
// returns nil or ValidationErrors ( []FieldError )
err := validate.Struct(user)
if err != nil {
// this check is only needed when your code could produce
// an invalid value for validation such as interface with nil
// value most including myself do not usually have code like this.
if _, ok := err.(*validator.InvalidValidationError); ok {
fmt.Println(err)
return
}
for _, err := range err.(validator.ValidationErrors) {
fmt.Println(err.Namespace())
fmt.Println(err.Field())
fmt.Println(err.StructNamespace())
fmt.Println(err.StructField())
fmt.Println(err.Tag())
fmt.Println(err.ActualTag())
fmt.Println(err.Kind())
fmt.Println(err.Type())
fmt.Println(err.Value())
fmt.Println(err.Param())
fmt.Println()
}
// from here you can create your own error messages in whatever language you wish
return
}
// save user to database
}
func validateVariable() {
myEmail := "joeybloggs.gmail.com"
errs := validate.Var(myEmail, "required,email")
if errs != nil {
fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag
return
}
// email ok, move on
}
验证规则
字段验证规则
标签 | 说明 |
---|---|
eqcsfield | 字段等于另一个字段(相对) |
eqfield | 字段等于另一个字段 |
fieldcontains | 字段包含 |
fieldexcludes | 字段不包含 |
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 |