main.go 1.1 KB

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