golang常用库:字段参数验证库-validator

在平常开发中,特别是在web应用开发中,为了验证输入字段的合法性,都会做一些验证操作。比如对用户提交的表单字段进行验证,或者对请求的API接口字段进行验证,验证字段的合法性,保证输入字段值的安全,防止用户的恶意请求。

一般的做法是用正则表达式,一个字段一个字段的进行验证。一个一个字段验证的话,写起来比较繁琐。那有没更好的方法,进行字段的合法性验证?有, 这就是下面要介绍的 validator 这个验证组件。

代码地址:
https://github.com/go-playground/validator

文档地址:
https://github.com/go-playground/validator/blob/master/README.md

安装

go get:

go get github.com/go-playground/validator/v10

在文件中引用validator包:

import "github.com/go-playground/validator/v10"

validator使用

文档:

例子1:验证单个字段变量值

validation1.go

package main import ( "fmt" "github.com/go-playground/validator/v10" ) func main() { validate := validator.New() var boolTest bool err := validate.Var(boolTest, "required") if err != nil { fmt.Println(err) } var stringTest string = "" err = validate.Var(stringTest, "required") if err != nil { fmt.Println(err) } var emailTest string = "test@126.com" err = validate.Var(emailTest, "email") if err != nil { fmt.Println(err) } else { fmt.Println("success") // 输出: success。 说明验证成功 } emailTest2 := "test.126.com" errs := validate.Var(emailTest2, "required,email") if errs != nil { fmt.Println(errs) // 输出: Key: "" Error:Field validation for "" failed on the "email" tag。验证失败 } fmt.Println("\r\nEnd!!") }

运行输出:

go run simple1.go
Key: '' Error:Field validation for '' failed on the 'required' tag
Key: '' Error:Field validation for '' failed on the 'required' tag
success
Key: '' Error:Field validation for '' failed on the 'email' tag

End!!

例子2:验证结构体struct

from:struct validate

validation_struct.go,这个程序还列出了效验出错字段的一些信息,

package main import ( "fmt" "github.com/go-playground/validator/v10" ) type User struct { FirstName string `validate:"required"` LastName string `validate:"required"` Age uint8 `validate:"gte=0,lte=130"` Email string `validate:"required,email"` Addresses []*Address `validate:"required,dive,required"` } type Address struct { Street string `validate:"required"` City string `validate:"required"` Planet string `validate:"required"` Phone string `validate:"required"` } func main() { address := &Address{ Street: "Eavesdown Docks", Planet: "Persphone", Phone: "none", } user := &User{ FirstName: "Badger", LastName: "Smith", Age: 135, Email: "Badger.Smith@gmail.com", Addresses: []*Address{address}, } validate := validator.New() err := validate.Struct(user) if err != nil { fmt.Println("=== error msg ====") fmt.Println(err) if _, ok := err.(*validator.InvalidValidationError); ok { fmt.Println(err) return } fmt.Println("\r\n=========== error field info ====================") for _, err := range err.(validator.ValidationErrors) { // 列出效验出错字段的信息 fmt.Println("Namespace: ", err.Namespace()) fmt.Println("Fild: ", err.Field()) fmt.Println("StructNamespace: ", err.StructNamespace()) fmt.Println("StructField: ", err.StructField()) fmt.Println("Tag: ", err.Tag()) fmt.Println("ActualTag: ", err.ActualTag()) fmt.Println("Kind: ", err.Kind()) fmt.Println("Type: ", err.Type()) fmt.Println("Value: ", err.Value()) fmt.Println("Param: ", err.Param()) fmt.Println() } // from here you can create your own error messages in whatever language you wish return } }

运行 输出:

$ go run validation_struct.go
=== error msg ====
Key: 'User.Age' Error:Field validation for 'Age' failed on the 'lte' tag
Key: 'User.Addresses[0].City' Error:Field validation for 'City' failed on the 'required' tag

=========== error field info ====================
Namespace: User.Age
Fild: Age
StructNamespace: User.Age
StructField: Age
Tag: lte
ActualTag: lte
Kind: uint8
Type: uint8
Value: 135
Param: 130

Namespace: User.Addresses[0].City
Fild: City
StructNamespace: User.Addresses[0].City
StructField: City
Tag: required
ActualTag: required
Kind: string
Type: string
Value:
Param:

还可以给字段加一些其他tag信息,方面form,json的解析,如下:

type User struct { FirstName string `form:"firstname" json:"firstname" validate:"required"` LastName string `form:"lastname" json:"lastname" validate:"required"` Age uint8 ` form:"age" json:"age"validate:"gte=0,lte=130"` Email string ` form:"email" json:"email" validate:"required,email"` } 用户自定义函数验证

用户自定义函数验证字段是否合法,效验是否正确。

例子3: 通过字段tag自定义函数 validate.RegisterValidation

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsxgjp.html