Merge pull request #140 from joeybloggs/v6-development
Add RegisterCustomTypeFunc for easier adding of CustomTypeFuncpull/141/head
commit
442b210016
@ -0,0 +1,48 @@ |
||||
package main |
||||
|
||||
import ( |
||||
"database/sql" |
||||
"database/sql/driver" |
||||
"fmt" |
||||
"reflect" |
||||
|
||||
"gopkg.in/bluesuncorp/validator.v6" |
||||
) |
||||
|
||||
// DbBackedUser User struct
|
||||
type DbBackedUser struct { |
||||
Name sql.NullString `validate:"required"` |
||||
Age sql.NullInt64 `validate:"required"` |
||||
} |
||||
|
||||
func main() { |
||||
|
||||
config := validator.Config{ |
||||
TagName: "validate", |
||||
ValidationFuncs: validator.BakedInValidators, |
||||
} |
||||
|
||||
validate := validator.New(config) |
||||
|
||||
// register all sql.Null* types to use the ValidateValuer CustomTypeFunc
|
||||
validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{}) |
||||
|
||||
x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}} |
||||
errs := validate.Struct(x) |
||||
|
||||
if len(errs) > 0 { |
||||
fmt.Printf("Errs:\n%+v\n", errs) |
||||
} |
||||
} |
||||
|
||||
// ValidateValuer implements validator.CustomTypeFunc
|
||||
func ValidateValuer(field reflect.Value) interface{} { |
||||
if valuer, ok := field.Interface().(driver.Valuer); ok { |
||||
val, err := valuer.Value() |
||||
if err == nil { |
||||
return val |
||||
} |
||||
// handle the error how you want
|
||||
} |
||||
return nil |
||||
} |
Loading…
Reference in new issue