Skip to content

Commit 946d444

Browse files
author
Dean Karn
committed
Add custom validation example
1 parent a021b2e commit 946d444

File tree

1 file changed

+39
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)