Skip to content

Commit

Permalink
👔 up: update IsEmpty check func, add test case for issue 276
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Dec 11, 2024
1 parent c3621d4 commit ba31b00
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
18 changes: 18 additions & 0 deletions issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1757,3 +1757,21 @@ func TestIssues_255(t *testing.T) {
assert.Equal(t, []string{"foobar"}, *req.PtrStringSlice)
})
}

// https://github.com/gookit/validate/issues/276
// Struct validation: invalid memory address or nil pointer dereference #276
func TestIssues_276(t *testing.T) {
type user struct {
Name string `validate:"required"`
Age int `validate:"required_if:Name,lee"`
}

u := &user{Name: "lee"}
v := validate.Struct(u)

assert.False(t, v.Validate())
fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
fmt.Println(v.Errors.OneError()) // returns a random error
fmt.Println(v.Errors.Field("Age")) // returns error messages of the field
}
12 changes: 10 additions & 2 deletions validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,11 +462,19 @@ func IsEmpty(val any) bool {
if val == nil {
return true
}

if s, ok := val.(string); ok {
return s == ""
}
return ValueIsEmpty(reflect.ValueOf(val))

var rv reflect.Value

// type check val is reflect.Value
if v2, ok := val.(reflect.Value); ok {
rv = v2
} else {
rv = reflect.ValueOf(val)
}
return ValueIsEmpty(rv)
}

// Contains check that the specified string, list(array, slice) or map contains the
Expand Down

0 comments on commit ba31b00

Please sign in to comment.