Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/gookit/validate
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jan 8, 2021
2 parents 90192b8 + 948c82e commit 84026e0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
6 changes: 3 additions & 3 deletions data_source.go
Expand Up @@ -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() != "<invalid Value>" {
if tft.Anonymous {
fv = d.value.FieldByName(subField)
d.fieldNames[field] = 1

} else {
// get parent struct
fv = d.value.FieldByName(parentField)
Expand Down
5 changes: 2 additions & 3 deletions issues_test.go
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down
27 changes: 25 additions & 2 deletions validators.go
Expand Up @@ -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
Expand All @@ -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
}
Expand Down

0 comments on commit 84026e0

Please sign in to comment.