#初めに
GolangでのValidationチェックを実施する記事です。
#サンプルコード
main.go
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: "Badger.Smith@gmail.com",
FavouriteColor: "#000-",
Addresses: []*Address{address},
}
err := validate.Struct(user)
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
fmt.Println(err)
return
}
for _, err := range err.(validator.ValidationErrors) {
fmt.Println("=====================【validateチェック】===========================")
fmt.Println("1: " + err.Namespace())
fmt.Println("2: " + err.Field())
fmt.Println("3: " + err.StructNamespace())
fmt.Println("4: " + err.StructField())
fmt.Println("5: " + err.Tag())
fmt.Println("6: " + err.ActualTag())
fmt.Println(err.Kind())
fmt.Println(err.Type())
fmt.Println(err.Value())
fmt.Println("10" + 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
}
○実行結果
main.go
=====================【validateチェック】===========================
1: User.Addresses[0].City
2: City
3: User.Addresses[0].City
4: City
5: required
6: required
string
string
10
====================================================================
Key: '' Error:Field validation for '' failed on the 'email' tag
うーん、なかなか分かりづらいですね。。。
下記、URLがわかりやすかったので、乗っけておきます。
○追記
ozzo-validationチェックが使いやすかったので、こっちおすすめです。mattnさんの記事を乗っけておきます!!!
https://zenn.dev/mattn/articles/893f28eff96129
→さっくさく作れるので楽しいですね!!!
○参考文献