You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.1 KiB
52 lines
1.1 KiB
9 years ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"database/sql/driver"
|
||
|
"fmt"
|
||
|
"reflect"
|
||
|
|
||
8 years ago
|
"gopkg.in/go-playground/validator.v9"
|
||
9 years ago
|
)
|
||
|
|
||
9 years ago
|
// DbBackedUser User struct
|
||
9 years ago
|
type DbBackedUser struct {
|
||
|
Name sql.NullString `validate:"required"`
|
||
|
Age sql.NullInt64 `validate:"required"`
|
||
|
}
|
||
|
|
||
8 years ago
|
// use a single instance of Validate, it caches struct info
|
||
|
var validate *validator.Validate
|
||
9 years ago
|
|
||
8 years ago
|
func main() {
|
||
9 years ago
|
|
||
8 years ago
|
validate = validator.New()
|
||
9 years ago
|
|
||
|
// register all sql.Null* types to use the ValidateValuer CustomTypeFunc
|
||
|
validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
|
||
|
|
||
8 years ago
|
// build object for validation
|
||
9 years ago
|
x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}}
|
||
|
|
||
8 years ago
|
err := validate.Struct(x)
|
||
|
|
||
|
if err != nil {
|
||
|
fmt.Printf("Err(s):\n%+v\n", err)
|
||
9 years ago
|
}
|
||
|
}
|
||
|
|
||
|
// ValidateValuer implements validator.CustomTypeFunc
|
||
|
func ValidateValuer(field reflect.Value) interface{} {
|
||
8 years ago
|
|
||
9 years ago
|
if valuer, ok := field.Interface().(driver.Valuer); ok {
|
||
8 years ago
|
|
||
9 years ago
|
val, err := valuer.Value()
|
||
|
if err == nil {
|
||
|
return val
|
||
|
}
|
||
|
// handle the error how you want
|
||
|
}
|
||
8 years ago
|
|
||
9 years ago
|
return nil
|
||
|
}
|