💯Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MyStruct ..
|
|
|
|
type MyStruct struct {
|
|
|
|
String string `validate:"is-awesome"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// use a single instance of Validate, it caches struct info
|
|
|
|
var validate *validator.Validate
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
|
|
|
validate = validator.New()
|
|
|
|
validate.RegisterValidation("is-awesome", ValidateMyVal)
|
|
|
|
|
|
|
|
s := MyStruct{String: "awesome"}
|
|
|
|
|
|
|
|
err := validate.Struct(s)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Err(s):\n%+v\n", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.String = "not awesome"
|
|
|
|
err = validate.Struct(s)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Err(s):\n%+v\n", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateMyVal implements validator.Func
|
|
|
|
func ValidateMyVal(fl validator.FieldLevel) bool {
|
|
|
|
return fl.Field().String() == "awesome"
|
|
|
|
}
|