Skip to content

Commit

Permalink
Merge pull request #67 from fishyww/Support-custom-type-verification
Browse files Browse the repository at this point in the history
Support custom type verification
  • Loading branch information
inhere committed Jan 8, 2021
2 parents 421e016 + e1d1563 commit 948c82e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
5 changes: 2 additions & 3 deletions issues_test.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 948c82e

Please sign in to comment.