OSDN Git Service

new repo
[bytom/vapor.git] / vendor / gopkg.in / go-playground / validator.v9 / _examples / custom / main.go
1 package main
2
3 import (
4         "database/sql"
5         "database/sql/driver"
6         "fmt"
7         "reflect"
8
9         "gopkg.in/go-playground/validator.v9"
10 )
11
12 // DbBackedUser User struct
13 type DbBackedUser struct {
14         Name sql.NullString `validate:"required"`
15         Age  sql.NullInt64  `validate:"required"`
16 }
17
18 // use a single instance of Validate, it caches struct info
19 var validate *validator.Validate
20
21 func main() {
22
23         validate = validator.New()
24
25         // register all sql.Null* types to use the ValidateValuer CustomTypeFunc
26         validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
27
28         // build object for validation
29         x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}}
30
31         err := validate.Struct(x)
32
33         if err != nil {
34                 fmt.Printf("Err(s):\n%+v\n", err)
35         }
36 }
37
38 // ValidateValuer implements validator.CustomTypeFunc
39 func ValidateValuer(field reflect.Value) interface{} {
40
41         if valuer, ok := field.Interface().(driver.Valuer); ok {
42
43                 val, err := valuer.Value()
44                 if err == nil {
45                         return val
46                 }
47                 // handle the error how you want
48         }
49
50         return nil
51 }