From e1d1563b0b04294f2efe6b86d5077f137f227a54 Mon Sep 17 00:00:00 2001 From: fishyww Date: Tue, 24 Nov 2020 17:20:08 +0800 Subject: [PATCH 1/2] Support custom type verification --- issues_test.go | 5 ++--- validators.go | 27 +++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/issues_test.go b/issues_test.go index 774e68e..c2c7463 100644 --- a/issues_test.go +++ b/issues_test.go @@ -177,8 +177,7 @@ func TestIssues34(t *testing.T) { dump.Println(Enum(s1, []int{1, 2, 3, 4}), Enum(int32(s1), []int{1, 2, 3, 4})) - v.Validate() - + assert.True(t,v.Validate()) dump.Println(v.Errors) type someMode string @@ -189,7 +188,7 @@ func TestIssues34(t *testing.T) { v.StringRules(MS{ "mode": "required|in:abc,def", }) - v.Validate() + assert.True(t,v.Validate()) dump.Println(v.Errors) } diff --git a/validators.go b/validators.go index b40eae5..d1352ca 100644 --- a/validators.go +++ b/validators.go @@ -1098,14 +1098,37 @@ func Between(val interface{}, min, max int64) bool { * global: array, slice, map validators *************************************************************/ +// convert custom type to int or string or unit +func convert(val interface{})(value interface{},err error) { + + v := reflect.ValueOf(val) + + switch v.Kind() { + case reflect.String: + value = v.String() + case reflect.Int,reflect.Int8,reflect.Int16,reflect.Int32,reflect.Int64: + value = v.Int() + case reflect.Uint,reflect.Uint8,reflect.Uint16,reflect.Uint32,reflect.Uint64: + value = v.Uint() + default: + err = errConvertFail + } + + return +} + // Enum value(int(X),string) should be in the given enum(strings, ints, uints). func Enum(val, enum interface{}) bool { if val == nil || enum == nil { return false } + v,err := convert(val) + if err != nil { + return false + } // if is string value - if strVal, ok := val.(string); ok { + if strVal, ok := v.(string); ok { if ss, ok := enum.([]string); ok { for _, strItem := range ss { if strVal == strItem { // exists @@ -1118,7 +1141,7 @@ func Enum(val, enum interface{}) bool { } // as int value - intVal, err := mathutil.Int64(val) + intVal, err := mathutil.Int64(v) if err != nil { return false } From 201defd8a470628ca2c02301d702e147509eff7b Mon Sep 17 00:00:00 2001 From: fishyww Date: Sat, 12 Dec 2020 16:41:30 +0800 Subject: [PATCH 2/2] Modify the logic of anonymous fields --- data_source.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/data_source.go b/data_source.go index 80c3ae6..eee3de9 100644 --- a/data_source.go +++ b/data_source.go @@ -408,11 +408,11 @@ func (d *StructData) Get(field string) (interface{}, bool) { if t.Kind() != reflect.Struct { // not found OR not a struct return nil, false } + // whether it is an anonymous field - fv = d.value.FieldByName(subField) - if fv.String() != "" { + if tft.Anonymous { + fv = d.value.FieldByName(subField) d.fieldNames[field] = 1 - } else { // get parent struct fv = d.value.FieldByName(parentField)