From 715aa553c8a1f4d76186a793b7d86c14b10301e5 Mon Sep 17 00:00:00 2001 From: Joel Williams Date: Wed, 2 Sep 2015 23:42:58 +0200 Subject: [PATCH 1/2] Added checking for nil receiver on Validator methods --- README.md | 6 +++--- validator.go | 26 +++++++++++++++++++++----- validator_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6bf0949..d9e66c2 100644 --- a/README.md +++ b/README.md @@ -225,9 +225,9 @@ How to Contribute There will always be a development branch for each version i.e. `v1-development`. In order to contribute, please make your pull requests against those branches. -If the changes being proposed or requested are breaking changes, please create an issue, for discussion -or create a pull request against the highest development branch for example this package has a -v1 and v1-development branch however, there will also be a v2-development brach even though v2 doesn't exist yet. +If the changes being proposed or requested are breaking changes, please create an issue, for discussion +or create a pull request against the highest development branch for example this package has a +v1 and v1-development branch however, there will also be a v2-development branch even though v2 doesn't exist yet. I strongly encourage everyone whom creates a custom validation function to contribute them and help make this package even better. diff --git a/validator.go b/validator.go index 3542569..c5436db 100644 --- a/validator.go +++ b/validator.go @@ -146,7 +146,9 @@ func New(config Config) *Validate { // NOTE: if the key already exists, the previous validation function will be replaced. // NOTE: this method is not thread-safe func (v *Validate) RegisterValidation(key string, f Func) error { - + if v == nil { + panic("Validate.RegisterValidation called with nil receiver") + } if len(key) == 0 { return errors.New("Function Key cannot be empty") } @@ -162,6 +164,9 @@ func (v *Validate) RegisterValidation(key string, f Func) error { // RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { + if v == nil { + panic("Validate.RegisterCustomTypeFunc called with nil receiver") + } if v.config.CustomTypeFuncs == nil { v.config.CustomTypeFuncs = map[reflect.Type]CustomTypeFunc{} @@ -178,7 +183,9 @@ func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{ // NOTE: it returns ValidationErrors instead of a single FieldError because this can also // validate Array, Slice and maps fields which may contain more than one error func (v *Validate) Field(field interface{}, tag string) ValidationErrors { - + if v == nil { + panic("Validate.Field called with nil receiver") + } errs := errsPool.Get().(ValidationErrors) fieldVal := reflect.ValueOf(field) @@ -196,6 +203,9 @@ func (v *Validate) Field(field interface{}, tag string) ValidationErrors { // NOTE: it returns ValidationErrors instead of a single FieldError because this can also // validate Array, Slice and maps fields which may contain more than one error func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string) ValidationErrors { + if v == nil { + panic("Validate.FieldWithValue called with nil receiver") + } errs := errsPool.Get().(ValidationErrors) topVal := reflect.ValueOf(val) @@ -216,7 +226,9 @@ func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string // NOTE: This is normally not needed, however in some specific cases such as: tied to a // legacy data structure, it will be useful func (v *Validate) StructPartial(current interface{}, fields ...string) ValidationErrors { - + if v == nil { + panic("Validate.StructPartial called with nil receiver") + } sv, _ := v.extractType(reflect.ValueOf(current)) name := sv.Type().Name() m := map[string]*struct{}{} @@ -274,7 +286,9 @@ func (v *Validate) StructPartial(current interface{}, fields ...string) Validati // NOTE: This is normally not needed, however in some specific cases such as: tied to a // legacy data structure, it will be useful func (v *Validate) StructExcept(current interface{}, fields ...string) ValidationErrors { - + if v == nil { + panic("Validate.StructExcept called with nil receiver") + } sv, _ := v.extractType(reflect.ValueOf(current)) name := sv.Type().Name() m := map[string]*struct{}{} @@ -297,7 +311,9 @@ func (v *Validate) StructExcept(current interface{}, fields ...string) Validatio // Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. func (v *Validate) Struct(current interface{}) ValidationErrors { - + if v == nil { + panic("Validate.Struct called with nil receiver") + } errs := errsPool.Get().(ValidationErrors) sv := reflect.ValueOf(current) diff --git a/validator_test.go b/validator_test.go index 22084b4..0a12d50 100644 --- a/validator_test.go +++ b/validator_test.go @@ -210,6 +210,31 @@ type TestPartial struct { } } +func TestNilValidator(t *testing.T) { + + type TestStruct struct { + Test string `validate:"required"` + } + + ts := TestStruct{} + + var val *Validate + + fn := func(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { + + return current.String() == field.String() + } + + PanicMatches(t, func() { val.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{}) }, "Validate.RegisterCustomTypeFunc called with nil receiver") + PanicMatches(t, func() { val.RegisterValidation("something", fn) }, "Validate.RegisterValidation called with nil receiver") + PanicMatches(t, func() { val.Field(ts.Test, "required") }, "Validate.Field called with nil receiver") + PanicMatches(t, func() { val.FieldWithValue("test", ts.Test, "required") }, "Validate.FieldWithValue called with nil receiver") + PanicMatches(t, func() { val.Struct(ts) }, "Validate.Struct called with nil receiver") + PanicMatches(t, func() { val.StructExcept(ts, "Test") }, "Validate.StructExcept called with nil receiver") + PanicMatches(t, func() { val.StructPartial(ts, "Test") }, "Validate.StructPartial called with nil receiver") + +} + func TestStructPartial(t *testing.T) { p1 := []string{ From 14df41612656da974670e1b3849367e0c91d2e4a Mon Sep 17 00:00:00 2001 From: joeybloggs Date: Wed, 2 Sep 2015 20:13:22 -0400 Subject: [PATCH 2/2] Update Validator instance check * change for one validator instance method and message --- validator.go | 70 +++++++++++++++++++++++------------------------ validator_test.go | 14 +++++----- 2 files changed, 41 insertions(+), 43 deletions(-) diff --git a/validator.go b/validator.go index c5436db..25a1bd2 100644 --- a/validator.go +++ b/validator.go @@ -20,21 +20,22 @@ import ( ) const ( - utf8HexComma = "0x2C" - utf8Pipe = "0x7C" - tagSeparator = "," - orSeparator = "|" - tagKeySeparator = "=" - structOnlyTag = "structonly" - omitempty = "omitempty" - skipValidationTag = "-" - diveTag = "dive" - existsTag = "exists" - fieldErrMsg = "Key: \"%s\" Error:Field validation for \"%s\" failed on the \"%s\" tag" - arrayIndexFieldName = "%s" + leftBracket + "%d" + rightBracket - mapIndexFieldName = "%s" + leftBracket + "%v" + rightBracket - invalidValidation = "Invalid validation tag on field %s" - undefinedValidation = "Undefined validation function on field %s" + utf8HexComma = "0x2C" + utf8Pipe = "0x7C" + tagSeparator = "," + orSeparator = "|" + tagKeySeparator = "=" + structOnlyTag = "structonly" + omitempty = "omitempty" + skipValidationTag = "-" + diveTag = "dive" + existsTag = "exists" + fieldErrMsg = "Key: \"%s\" Error:Field validation for \"%s\" failed on the \"%s\" tag" + arrayIndexFieldName = "%s" + leftBracket + "%d" + rightBracket + mapIndexFieldName = "%s" + leftBracket + "%v" + rightBracket + invalidValidation = "Invalid validation tag on field %s" + undefinedValidation = "Undefined validation function on field %s" + validatorNotInitialized = "Validator instance not initialized" ) var ( @@ -78,6 +79,12 @@ type Validate struct { config Config } +func (v *Validate) initCheck() { + if v == nil { + panic(validatorNotInitialized) + } +} + // Config contains the options that a Validator instance will use. // It is passed to the New() function type Config struct { @@ -146,9 +153,8 @@ func New(config Config) *Validate { // NOTE: if the key already exists, the previous validation function will be replaced. // NOTE: this method is not thread-safe func (v *Validate) RegisterValidation(key string, f Func) error { - if v == nil { - panic("Validate.RegisterValidation called with nil receiver") - } + v.initCheck() + if len(key) == 0 { return errors.New("Function Key cannot be empty") } @@ -164,9 +170,7 @@ func (v *Validate) RegisterValidation(key string, f Func) error { // RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { - if v == nil { - panic("Validate.RegisterCustomTypeFunc called with nil receiver") - } + v.initCheck() if v.config.CustomTypeFuncs == nil { v.config.CustomTypeFuncs = map[reflect.Type]CustomTypeFunc{} @@ -183,9 +187,8 @@ func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{ // NOTE: it returns ValidationErrors instead of a single FieldError because this can also // validate Array, Slice and maps fields which may contain more than one error func (v *Validate) Field(field interface{}, tag string) ValidationErrors { - if v == nil { - panic("Validate.Field called with nil receiver") - } + v.initCheck() + errs := errsPool.Get().(ValidationErrors) fieldVal := reflect.ValueOf(field) @@ -203,9 +206,7 @@ func (v *Validate) Field(field interface{}, tag string) ValidationErrors { // NOTE: it returns ValidationErrors instead of a single FieldError because this can also // validate Array, Slice and maps fields which may contain more than one error func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string) ValidationErrors { - if v == nil { - panic("Validate.FieldWithValue called with nil receiver") - } + v.initCheck() errs := errsPool.Get().(ValidationErrors) topVal := reflect.ValueOf(val) @@ -226,9 +227,8 @@ func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string // NOTE: This is normally not needed, however in some specific cases such as: tied to a // legacy data structure, it will be useful func (v *Validate) StructPartial(current interface{}, fields ...string) ValidationErrors { - if v == nil { - panic("Validate.StructPartial called with nil receiver") - } + v.initCheck() + sv, _ := v.extractType(reflect.ValueOf(current)) name := sv.Type().Name() m := map[string]*struct{}{} @@ -286,9 +286,8 @@ func (v *Validate) StructPartial(current interface{}, fields ...string) Validati // NOTE: This is normally not needed, however in some specific cases such as: tied to a // legacy data structure, it will be useful func (v *Validate) StructExcept(current interface{}, fields ...string) ValidationErrors { - if v == nil { - panic("Validate.StructExcept called with nil receiver") - } + v.initCheck() + sv, _ := v.extractType(reflect.ValueOf(current)) name := sv.Type().Name() m := map[string]*struct{}{} @@ -311,9 +310,8 @@ func (v *Validate) StructExcept(current interface{}, fields ...string) Validatio // Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. func (v *Validate) Struct(current interface{}) ValidationErrors { - if v == nil { - panic("Validate.Struct called with nil receiver") - } + v.initCheck() + errs := errsPool.Get().(ValidationErrors) sv := reflect.ValueOf(current) diff --git a/validator_test.go b/validator_test.go index 0a12d50..36e2724 100644 --- a/validator_test.go +++ b/validator_test.go @@ -225,13 +225,13 @@ func TestNilValidator(t *testing.T) { return current.String() == field.String() } - PanicMatches(t, func() { val.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{}) }, "Validate.RegisterCustomTypeFunc called with nil receiver") - PanicMatches(t, func() { val.RegisterValidation("something", fn) }, "Validate.RegisterValidation called with nil receiver") - PanicMatches(t, func() { val.Field(ts.Test, "required") }, "Validate.Field called with nil receiver") - PanicMatches(t, func() { val.FieldWithValue("test", ts.Test, "required") }, "Validate.FieldWithValue called with nil receiver") - PanicMatches(t, func() { val.Struct(ts) }, "Validate.Struct called with nil receiver") - PanicMatches(t, func() { val.StructExcept(ts, "Test") }, "Validate.StructExcept called with nil receiver") - PanicMatches(t, func() { val.StructPartial(ts, "Test") }, "Validate.StructPartial called with nil receiver") + PanicMatches(t, func() { val.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{}) }, validatorNotInitialized) + PanicMatches(t, func() { val.RegisterValidation("something", fn) }, validatorNotInitialized) + PanicMatches(t, func() { val.Field(ts.Test, "required") }, validatorNotInitialized) + PanicMatches(t, func() { val.FieldWithValue("test", ts.Test, "required") }, validatorNotInitialized) + PanicMatches(t, func() { val.Struct(ts) }, validatorNotInitialized) + PanicMatches(t, func() { val.StructExcept(ts, "Test") }, validatorNotInitialized) + PanicMatches(t, func() { val.StructPartial(ts, "Test") }, validatorNotInitialized) }