Add custom validation example
Dean Karn
6 years ago
0 | package main | |
1 | ||
2 | import ( | |
3 | "fmt" | |
4 | ||
5 | "gopkg.in/go-playground/validator.v9" | |
6 | ) | |
7 | ||
8 | // MyStruct .. | |
9 | type MyStruct struct { | |
10 | String string `validate:"is-awesome"` | |
11 | } | |
12 | ||
13 | // use a single instance of Validate, it caches struct info | |
14 | var validate *validator.Validate | |
15 | ||
16 | func main() { | |
17 | ||
18 | validate = validator.New() | |
19 | validate.RegisterValidation("is-awesome", ValidateMyVal) | |
20 | ||
21 | s := MyStruct{String: "awesome"} | |
22 | ||
23 | err := validate.Struct(s) | |
24 | if err != nil { | |
25 | fmt.Printf("Err(s):\n%+v\n", err) | |
26 | } | |
27 | ||
28 | s.String = "not awesome" | |
29 | err = validate.Struct(s) | |
30 | if err != nil { | |
31 | fmt.Printf("Err(s):\n%+v\n", err) | |
32 | } | |
33 | } | |
34 | ||
35 | // ValidateMyVal implements validator.Func | |
36 | func ValidateMyVal(fl validator.FieldLevel) bool { | |
37 | return fl.Field().String() == "awesome" | |
38 | } |