Skip to content

Commit 7c84489

Browse files
author
Kevin Harrington
committed
Added RegisterCustomTypeFunc method and usage example.
1 parent 048d7b8 commit 7c84489

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

examples/custom.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package main
2+
3+
import (
4+
"database/sql"
5+
"database/sql/driver"
6+
"fmt"
7+
"reflect"
8+
9+
validator "gopkg.in/bluesuncorp/validator.v6"
10+
)
11+
12+
type DbBackedUser struct {
13+
Name sql.NullString `validate:"required"`
14+
Age sql.NullInt64 `validate:"required"`
15+
}
16+
17+
func main() {
18+
19+
config := validator.Config{
20+
TagName: "validate",
21+
ValidationFuncs: validator.BakedInValidators,
22+
}
23+
24+
validate := validator.New(config)
25+
26+
// register all sql.Null* types to use the ValidateValuer CustomTypeFunc
27+
validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
28+
29+
x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}}
30+
errs := validate.Struct(x)
31+
32+
if len(errs) > 0 {
33+
fmt.Printf("Errs:\n%+v\n", errs)
34+
}
35+
}
36+
37+
// ValidateValuer implements validator.CustomTypeFunc
38+
func ValidateValuer(field reflect.Value) interface{} {
39+
if valuer, ok := field.Interface().(driver.Valuer); ok {
40+
val, err := valuer.Value()
41+
if err == nil {
42+
return val
43+
}
44+
// handle the error how you want
45+
}
46+
return nil
47+
}

validator.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,17 @@ func (v *Validate) RegisterValidation(key string, f Func) error {
157157
return nil
158158
}
159159

160+
// RegisterCustomTypeFunc registers types w/a custom type handler function.
161+
func (v *Validate) RegisterCustomTypeFunc(f CustomTypeFunc, sampleTypeValues ...interface{}) {
162+
if v.config.CustomTypeFuncs == nil {
163+
v.config.CustomTypeFuncs = map[reflect.Type]CustomTypeFunc{}
164+
}
165+
for _, sample := range sampleTypeValues {
166+
v.config.CustomTypeFuncs[reflect.TypeOf(sample)] = f
167+
}
168+
v.config.hasCustomFuncs = true
169+
}
170+
160171
// Field validates a single field using tag style validation and returns ValidationErrors
161172
// NOTE: it returns ValidationErrors instead of a single FieldError because this can also
162173
// validate Array, Slice and maps fields which may contain more than one error

0 commit comments

Comments
 (0)