...
1 package main
2
3 import (
4 "database/sql"
5 "database/sql/driver"
6 "fmt"
7 "reflect"
8
9 "github.com/go-playground/validator/v10"
10 )
11
12
13 type DbBackedUser struct {
14 Name sql.NullString `validate:"required"`
15 Age sql.NullInt64 `validate:"required"`
16 }
17
18
19 var validate *validator.Validate
20
21 func main() {
22
23 validate = validator.New()
24
25
26 validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
27
28
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
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
48 }
49
50 return nil
51 }
52
View as plain text