前言
在web應(yīng)用中經(jīng)常會遇到數(shù)據(jù)驗證問題,普通的驗證方法比較繁瑣,這里介紹一個使用比較多的包validator。
原理
將驗證規(guī)則寫在struct對字段tag里,再通過反射(reflect)獲取struct的tag,實現(xiàn)數(shù)據(jù)驗證。
安裝
go get github.com/go-playground/validator/v10
示例
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type Users struct {
Phone string `form:"phone" json:"phone" validate:"required"`
Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"`
Code string `form:"code" json:"code" validate:"required,len=6"`
}
func main() {
users := Users{
Phone: "1326654487",
Passwd: "123",
Code: "123456",
}
validate := validator.New()
err := validate.Struct(users)
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
fmt.Println(err)//Key: 'Users.Passwd' Error:Field validation for 'Passwd' failed on the 'min' tag
return
}
}
return
}
驗證規(guī)則
- required :必填
- email:驗證字符串是email格式;例:“email”
- url:這將驗證字符串值包含有效的網(wǎng)址;例:“url”
- max:字符串最大長度;例:“max=20”
- min:字符串最小長度;例:“min=6”
- excludesall:不能包含特殊字符;例:“excludesall=0x2C”//注意這里用十六進制表示。
- len:字符長度必須等于n,或者數(shù)組、切片、map的len值為n,即包含的項目數(shù);例:“l(fā)en=6”
- eq:數(shù)字等于n,或者或者數(shù)組、切片、map的len值為n,即包含的項目數(shù);例:“eq=6”
- ne:數(shù)字不等于n,或者或者數(shù)組、切片、map的len值不等于為n,即包含的項目數(shù)不為n,其和eq相反;例:“ne=6”
- gt:數(shù)字大于n,或者或者數(shù)組、切片、map的len值大于n,即包含的項目數(shù)大于n;例:“gt=6”
- gte:數(shù)字大于或等于n,或者或者數(shù)組、切片、map的len值大于或等于n,即包含的項目數(shù)大于或等于n;例:“gte=6”
- lt:數(shù)字小于n,或者或者數(shù)組、切片、map的len值小于n,即包含的項目數(shù)小于n;例:“l(fā)t=6”
- lte:數(shù)字小于或等于n,或者或者數(shù)組、切片、map的len值小于或等于n,即包含的項目數(shù)小于或等于n;例:“l(fā)te=6”
跨字段驗證
如想實現(xiàn)比較輸入密碼和確認密碼是否一致等類似場景
- eqfield=Field: 必須等于 Field 的值;
- nefield=Field: 必須不等于 Field 的值;
- gtfield=Field: 必須大于 Field 的值;
- gtefield=Field: 必須大于等于 Field 的值;
- ltfield=Field: 必須小于 Field 的值;
- ltefield=Field: 必須小于等于 Field 的值;
- eqcsfield=Other.Field: 必須等于 struct Other 中 Field 的值;
- necsfield=Other.Field: 必須不等于 struct Other 中 Field 的值;
- gtcsfield=Other.Field: 必須大于 struct Other 中 Field 的值;
- gtecsfield=Other.Field: 必須大于等于 struct Other 中 Field 的值;
- ltcsfield=Other.Field: 必須小于 struct Other 中 Field 的值;
- ltecsfield=Other.Field: 必須小于等于 struct Other 中 Field 的值;
示例
type UserReg struct {
Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"`
Repasswd string `form:"repasswd" json:"repasswd" validate:"required,max=20,min=6,eqfield=Passwd"`
}
示例驗證了Passwd,和Repasswd值是否相等。如想了解更多類型,請參考文檔 https://godoc.org/gopkg.in/go-playground/validator.v10
自定義驗證類型
示例:
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type Users struct {
Name string `form:"name" json:"name" validate:"required,CustomValidationErrors"`//包含自定義函數(shù)
Age uint8 `form:"age" json:"age" validate:"required,gt=18"`
Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"`
Code string `form:"code" json:"code" validate:"required,len=6"`
}
func main() {
users := Users{
Name: "admin",
Age: 12,
Passwd: "123",
Code: "123456",
}
validate := validator.New()
//注冊自定義函數(shù)
_=validate.RegisterValidation("CustomValidationErrors", CustomValidationErrors)
err := validate.Struct(users)
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
fmt.Println(err)//Key: 'Users.Name' Error:Field validation for 'Name' failed on the 'CustomValidationErrors' tag
return
}
}
return
}
func CustomValidationErrors(fl validator.FieldLevel) bool {
return fl.Field().String() != "admin"
}
翻譯錯誤信息為中文
通過以上示例我們看到,validator默認的錯誤提示信息類似如下
Key: 'Users.Name' Error:Field validation for 'Name' failed on the 'CustomValidationErrors' tag
顯然這并不是我們想要,如想翻譯成中文,或其他語言怎么辦?go-playground上提供了很好的解決方法。
先自行安裝需要的兩個包
https://github.com/go-playground/locales
https://github.com/go-playground/universal-translator
執(zhí)行:
go get github.com/go-playground/universal-translator
go get github.com/go-playground/locales
示例:
package main
import (
"fmt"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
)
type Users struct {
Name string `form:"name" json:"name" validate:"required"`
Age uint8 `form:"age" json:"age" validate:"required,gt=18"`
Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"`
Code string `form:"code" json:"code" validate:"required,len=6"`
}
func main() {
users := Users{
Name: "admin",
Age: 12,
Passwd: "123",
Code: "123456",
}
uni := ut.New(zh.New())
trans, _ := uni.GetTranslator("zh")
validate := validator.New()
//驗證器注冊翻譯器
err := zh_translations.RegisterDefaultTranslations(validate, trans)
if err!=nil {
fmt.Println(err)
}
err = validate.Struct(users)
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
fmt.Println(err.Translate(trans))//Age必須大于18
return
}
}
return
}
輸出:
Age必須大于18
至此我們發(fā)現(xiàn)大部分錯誤信息已經(jīng)翻譯成中文,但字段名(Age)還是沒有翻譯,為了將字段名翻譯成中文,查了一些資料,https://www.jb51.net/article/197866.htm>,
照著做沒有成功(可能有遺漏吧),最后還是翻看了一下源代碼,在https://github.com/go-playground/validator/blob/master/validator_instance.go,第137行
// RegisterTagNameFunc registers a function to get alternate names for StructFields.
//
// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names:
//
// validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
// if name == "-" {
// return ""
// }
// return name
// })
其實原理就是注冊一個函數(shù),將struct tag里添加的中文名 作為備用名。
package main
import (
"fmt"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
"reflect"
)
type Users struct {
Name string `form:"name" json:"name" validate:"required" label:"用戶名"`
Age uint8 `form:"age" json:"age" validate:"required,gt=18" label:"年齡"`
Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"`
Code string `form:"code" json:"code" validate:"required,len=6"`
}
func main() {
users := Users{
Name: "admin",
Age: 12,
Passwd: "123",
Code: "123456",
}
uni := ut.New(zh.New())
trans, _ := uni.GetTranslator("zh")
validate := validator.New()
//注冊一個函數(shù),獲取struct tag里自定義的label作為字段名
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name:=fld.Tag.Get("label")
return name
})
//注冊翻譯器
err := zh_translations.RegisterDefaultTranslations(validate, trans)
if err!=nil {
fmt.Println(err)
}
err = validate.Struct(users)
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
fmt.Println(err.Translate(trans))//年齡必須大于18
return
}
}
return
}
輸出結(jié)果:
年齡必須大于18
gin 內(nèi)置的validator
gin已經(jīng)支持go-playground / validator / v10進行驗證。在此處查看有關(guān)標簽用法的完整文檔。
以下只提供了一個綁定ShouldBindWith示例,如需了解更多方法,進入這里。
示例
package main
import (
"fmt"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
"net/http"
"reflect"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
)
var trans ut.Translator
// Booking contains binded and validated data.
type Booking struct {
CheckIn time.Time `form:"check_in" json:"check_in" binding:"required,bookabledate" time_format:"2006-01-02" label:"輸入時間"`
CheckOut time.Time `form:"check_out" json:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02" label:"輸出時間"`
}
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
date, ok := fl.Field().Interface().(time.Time)
if ok {
today := time.Now()
if today.After(date) {
return false
}
}
return true
}
func main() {
route := gin.Default()
uni := ut.New(zh.New())
trans, _ = uni.GetTranslator("zh")
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
//注冊翻譯器
_= zh_translations.RegisterDefaultTranslations(v, trans)
//注冊自定義函數(shù)
_=v.RegisterValidation("bookabledate", bookableDate)
//注冊一個函數(shù),獲取struct tag里自定義的label作為字段名
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name:=fld.Tag.Get("label")
return name
})
//根據(jù)提供的標記注冊翻譯
v.RegisterTranslation("bookabledate", trans, func(ut ut.Translator) error {
return ut.Add("bookabledate", "{0}不能早于當前時間或{1}格式錯誤!", true)
}, func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T("bookabledate", fe.Field(), fe.Field())
return t
})
}
route.GET("/bookable", getBookable)
route.Run(":8085")
}
func getBookable(c *gin.Context) {
var b Booking
if err := c.ShouldBindWith(b, binding.Query); err == nil {
c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
} else {
errs := err.(validator.ValidationErrors)
fmt.Println(errs.Translate(trans))
//for _, e := range errs {
// // can translate each error one at a time.
// fmt.Println(e.Translate(trans))
//}
c.JSON(http.StatusBadRequest, gin.H{"error": errs.Translate(trans)})
}
}
運行程序,執(zhí)行以下命令
$ curl "localhost:8085/bookable?check_in=2018-04-16check_out=2018-04-16"
結(jié)果:
{"error":{"Booking.輸入時間":"輸入時間不能早于當前時間或輸入時間格式錯誤!","Booking.輸出時間":"輸出時間必須大于CheckIn"}}
查看以上結(jié)果我們發(fā)現(xiàn)翻譯還是不太完美,如規(guī)則中有g(shù)tfield的情況,字段(CheckIn)并沒有被翻譯。所以通過struct添加label的方式并不能從根本上解決字段翻譯問題。為了得到想要的結(jié)果,就需要將錯誤信息做單獨處理再輸出。
先定義翻譯庫
var BookingTrans =map[string]string{"CheckIn":"輸入時間","CheckOut":"輸出時間"}
再定義翻譯函數(shù)
func TransTagName(libTans,err interface{}) interface{} {
switch err.(type) {
case validator.ValidationErrorsTranslations:
var errs map[string]string
errs = make(map[string]string,0)
for k,v:=range err.(validator.ValidationErrorsTranslations){
for key,value:=range libTans.(map[string]string) {
v=strings.Replace(v,key,value,-1)
}
errs[k] = v
}
return errs
case string:
var errs string
for key,value:=range libTans.(map[string]string) {
errs=strings.Replace(errs,key,value,-1)
}
return errs
default:
return err
}
}
將原來翻譯錯誤信息的地方
修改為
msg:=TransTagName(BookingTrans,errs.Translate(trans))
fmt.Println(msg)
結(jié)果
{"error":{"Booking.輸入時間":"輸入時間不能早于當前時間或輸入時間格式錯誤!","Booking.輸出時間":"輸出時間必須大于輸入時間"}}
小結(jié):
1.gin 已經(jīng)支持validator最新的v10。
2.validator數(shù)據(jù)驗證順序struct字段從上往下,單個字段規(guī)則(binding:"gt=0,lt=2`),先左后右。
參考:
https://github.com/go-playground/validator
https://github.com/gin-gonic/gin
https://gitissue.com/issues/5d06a73965d56f73569b825f
https://segmentfault.com/a/1190000022527284
到此這篇關(guān)于golang之數(shù)據(jù)驗證validator的實現(xiàn)的文章就介紹到這了,更多相關(guān)golang 數(shù)據(jù)驗證validator內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- golang之數(shù)據(jù)校驗的實現(xiàn)代碼示例
- golang常用庫之字段參數(shù)驗證庫-validator使用詳解
- golang validator參數(shù)校驗的實現(xiàn)