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
10 years ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"database/sql/driver"
|
||
|
"fmt"
|
||
|
"reflect"
|
||
|
|
||
9 years ago
|
"gopkg.in/go-playground/validator.v9"
|
||
10 years ago
|
)
|
||
|
|
||
10 years ago
|
// DbBackedUser User struct
|
||
10 years ago
|
type DbBackedUser struct {
|
||
|
Name sql.NullString `validate:"required"`
|
||
|
Age sql.NullInt64 `validate:"required"`
|
||
|
}
|
||
|
|
||
9 years ago
|
// use a single instance of Validate, it caches struct info
|
||
|
var validate *validator.Validate
|
||
10 years ago
|
|
||
9 years ago
|
func main() {
|
||
10 years ago
|
|
||
9 years ago
|
validate = validator.New()
|
||
10 years ago
|
|
||
|
// register all sql.Null* types to use the ValidateValuer CustomTypeFunc
|
||
|
validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
|
||
|
|
||
9 years ago
|
// build object for validation
|
||
10 years ago
|
x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}}
|
||
|
|
||
9 years ago
|
err := validate.Struct(x)
|
||
|
|
||
|
if err != nil {
|
||
|
fmt.Printf("Err(s):\n%+v\n", err)
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
// ValidateValuer implements validator.CustomTypeFunc
|
||
|
func ValidateValuer(field reflect.Value) interface{} {
|
||
9 years ago
|
|
||
10 years ago
|
if valuer, ok := field.Interface().(driver.Valuer); ok {
|
||
9 years ago
|
|
||
10 years ago
|
val, err := valuer.Value()
|
||
|
if err == nil {
|
||
|
return val
|
||
|
}
|
||
|
// handle the error how you want
|
||
|
}
|
||
9 years ago
|
|
||
10 years ago
|
return nil
|
||
|
}
|