golang校驗結構體欄位的庫validator的使用
阿新 • • 發佈:2022-12-02
package scripts_stroage import ( "fmt" "github.com/go-playground/validator/v10" "testing" ) // 參考部落格: // https://juejin.cn/post/6900375680358285325 // https://www.cnblogs.com/jiujuan/p/13823864.html type VIPUser struct { // 1 <= len <= 20,不能為空 Name string `json:"name" validate:"required,min=1,max=20"` // 18 <= age <= 80 Age int `json:"age" validate:"required,min=18,max=80"` // 1<= len <= 64 Email string `json:"email" validate:"min=1,max=64"` } func TestTV1(t *testing.T) { // 0: vip0 := VIPUser{ Name: "naruto", Age: 22, Email: "[email protected]", } va0 := validator.New() err0 := va0.Struct(vip0) if err0 != nil { fmt.Println("err0: ", err0) // 輸入合法沒有列印 } // 1: vip1 := VIPUser{ Name: "whw", Email: "[email protected]", } va1 := validator.New() err1 := va1.Struct(vip1) if err1 != nil { fmt.Println("err1: ", err1) // err1: Key: 'VIPUser.Age' Error:Field validation for 'Age' failed on the 'required' tag } // 2: vip2 := VIPUser{ Name: "rrrrrrrrrrrrrrrrrrrrrrr", // name不合法 Age: 23, Email: "", // email不合法 } va2 := validator.New() err2 := va2.Struct(vip2) if err2 != nil { fmt.Println("err2: ", err2) /* err2: Key: 'VIPUser.Name' Error:Field validation for 'Name' failed on the 'max' tag Key: 'VIPUser.Email' Error:Field validation for 'Email' failed on the 'min' tag */ } // 3: vip3 := VIPUser{ Name: "whw", Age: 555, // age不合法 Email: "[email protected]", } va3 := validator.New() err3 := va3.Struct(vip3) if err3 != nil { fmt.Println("err3: ", err3) // err3: Key: 'VIPUser.Age' Error:Field validation for 'Age' failed on the 'max' tag } }
參考部落格:
https://juejin.cn/post/6900375680358285325
https://www.cnblogs.com/jiujuan/p/13823864.html