diff --git a/issues_test.go b/issues_test.go index d4215f4..054886d 100644 --- a/issues_test.go +++ b/issues_test.go @@ -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 +} diff --git a/validators.go b/validators.go index 9068431..d83d143 100644 --- a/validators.go +++ b/validators.go @@ -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