Skip to content

Commit 4d7f9e4

Browse files
Dean KarnDean Karn
authored andcommitted
Merge pull request #168 from bluesuncorp/v7-development
Update Validator Instance Check
2 parents f6ff3d4 + e66bd70 commit 4d7f9e4

File tree

3 files changed

+57
-18
lines changed

3 files changed

+57
-18
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,9 @@ How to Contribute
225225
There will always be a development branch for each version i.e. `v1-development`. In order to contribute,
226226
please make your pull requests against those branches.
227227

228-
If the changes being proposed or requested are breaking changes, please create an issue, for discussion
229-
or create a pull request against the highest development branch for example this package has a
230-
v1 and v1-development branch however, there will also be a v2-development brach even though v2 doesn't exist yet.
228+
If the changes being proposed or requested are breaking changes, please create an issue, for discussion
229+
or create a pull request against the highest development branch for example this package has a
230+
v1 and v1-development branch however, there will also be a v2-development branch even though v2 doesn't exist yet.
231231

232232
I strongly encourage everyone whom creates a custom validation function to contribute them and
233233
help make this package even better.

validator.go

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,22 @@ import (
2020
)
2121

2222
const (
23-
utf8HexComma = "0x2C"
24-
utf8Pipe = "0x7C"
25-
tagSeparator = ","
26-
orSeparator = "|"
27-
tagKeySeparator = "="
28-
structOnlyTag = "structonly"
29-
omitempty = "omitempty"
30-
skipValidationTag = "-"
31-
diveTag = "dive"
32-
existsTag = "exists"
33-
fieldErrMsg = "Key: \"%s\" Error:Field validation for \"%s\" failed on the \"%s\" tag"
34-
arrayIndexFieldName = "%s" + leftBracket + "%d" + rightBracket
35-
mapIndexFieldName = "%s" + leftBracket + "%v" + rightBracket
36-
invalidValidation = "Invalid validation tag on field %s"
37-
undefinedValidation = "Undefined validation function on field %s"
23+
utf8HexComma = "0x2C"
24+
utf8Pipe = "0x7C"
25+
tagSeparator = ","
26+
orSeparator = "|"
27+
tagKeySeparator = "="
28+
structOnlyTag = "structonly"
29+
omitempty = "omitempty"
30+
skipValidationTag = "-"
31+
diveTag = "dive"
32+
existsTag = "exists"
33+
fieldErrMsg = "Key: \"%s\" Error:Field validation for \"%s\" failed on the \"%s\" tag"
34+
arrayIndexFieldName = "%s" + leftBracket + "%d" + rightBracket
35+
mapIndexFieldName = "%s" + leftBracket + "%v" + rightBracket
36+
invalidValidation = "Invalid validation tag on field %s"
37+
undefinedValidation = "Undefined validation function on field %s"
38+
validatorNotInitialized = "Validator instance not initialized"
3839
)
3940

4041
var (
@@ -78,6 +79,12 @@ type Validate struct {
7879
config Config
7980
}
8081

82+
func (v *Validate) initCheck() {
83+
if v == nil {
84+
panic(validatorNotInitialized)
85+
}
86+
}
87+
8188
// Config contains the options that a Validator instance will use.
8289
// It is passed to the New() function
8390
type Config struct {
@@ -146,6 +153,7 @@ func New(config Config) *Validate {
146153
// NOTE: if the key already exists, the previous validation function will be replaced.
147154
// NOTE: this method is not thread-safe
148155
func (v *Validate) RegisterValidation(key string, f Func) error {
156+
v.initCheck()
149157

150158
if len(key) == 0 {
151159
return errors.New("Function Key cannot be empty")
@@ -162,6 +170,7 @@ func (v *Validate) RegisterValidation(key string, f Func) error {
162170

163171
// RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types
164172
func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) {
173+
v.initCheck()
165174

166175
if v.config.CustomTypeFuncs == nil {
167176
v.config.CustomTypeFuncs = map[reflect.Type]CustomTypeFunc{}
@@ -178,6 +187,7 @@ func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{
178187
// NOTE: it returns ValidationErrors instead of a single FieldError because this can also
179188
// validate Array, Slice and maps fields which may contain more than one error
180189
func (v *Validate) Field(field interface{}, tag string) ValidationErrors {
190+
v.initCheck()
181191

182192
errs := errsPool.Get().(ValidationErrors)
183193
fieldVal := reflect.ValueOf(field)
@@ -196,6 +206,7 @@ func (v *Validate) Field(field interface{}, tag string) ValidationErrors {
196206
// NOTE: it returns ValidationErrors instead of a single FieldError because this can also
197207
// validate Array, Slice and maps fields which may contain more than one error
198208
func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string) ValidationErrors {
209+
v.initCheck()
199210

200211
errs := errsPool.Get().(ValidationErrors)
201212
topVal := reflect.ValueOf(val)
@@ -216,6 +227,7 @@ func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string
216227
// NOTE: This is normally not needed, however in some specific cases such as: tied to a
217228
// legacy data structure, it will be useful
218229
func (v *Validate) StructPartial(current interface{}, fields ...string) ValidationErrors {
230+
v.initCheck()
219231

220232
sv, _ := v.extractType(reflect.ValueOf(current))
221233
name := sv.Type().Name()
@@ -274,6 +286,7 @@ func (v *Validate) StructPartial(current interface{}, fields ...string) Validati
274286
// NOTE: This is normally not needed, however in some specific cases such as: tied to a
275287
// legacy data structure, it will be useful
276288
func (v *Validate) StructExcept(current interface{}, fields ...string) ValidationErrors {
289+
v.initCheck()
277290

278291
sv, _ := v.extractType(reflect.ValueOf(current))
279292
name := sv.Type().Name()
@@ -297,6 +310,7 @@ func (v *Validate) StructExcept(current interface{}, fields ...string) Validatio
297310

298311
// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.
299312
func (v *Validate) Struct(current interface{}) ValidationErrors {
313+
v.initCheck()
300314

301315
errs := errsPool.Get().(ValidationErrors)
302316
sv := reflect.ValueOf(current)

validator_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,31 @@ type TestPartial struct {
210210
}
211211
}
212212

213+
func TestNilValidator(t *testing.T) {
214+
215+
type TestStruct struct {
216+
Test string `validate:"required"`
217+
}
218+
219+
ts := TestStruct{}
220+
221+
var val *Validate
222+
223+
fn := func(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
224+
225+
return current.String() == field.String()
226+
}
227+
228+
PanicMatches(t, func() { val.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{}) }, validatorNotInitialized)
229+
PanicMatches(t, func() { val.RegisterValidation("something", fn) }, validatorNotInitialized)
230+
PanicMatches(t, func() { val.Field(ts.Test, "required") }, validatorNotInitialized)
231+
PanicMatches(t, func() { val.FieldWithValue("test", ts.Test, "required") }, validatorNotInitialized)
232+
PanicMatches(t, func() { val.Struct(ts) }, validatorNotInitialized)
233+
PanicMatches(t, func() { val.StructExcept(ts, "Test") }, validatorNotInitialized)
234+
PanicMatches(t, func() { val.StructPartial(ts, "Test") }, validatorNotInitialized)
235+
236+
}
237+
213238
func TestStructPartial(t *testing.T) {
214239

215240
p1 := []string{

0 commit comments

Comments
 (0)