Skip to content

Commit ba31b00

Browse files
committed
👔 up: update IsEmpty check func, add test case for issue 276
1 parent c3621d4 commit ba31b00

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

issues_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -1757,3 +1757,21 @@ func TestIssues_255(t *testing.T) {
17571757
assert.Equal(t, []string{"foobar"}, *req.PtrStringSlice)
17581758
})
17591759
}
1760+
1761+
// https://github.com/gookit/validate/issues/276
1762+
// Struct validation: invalid memory address or nil pointer dereference #276
1763+
func TestIssues_276(t *testing.T) {
1764+
type user struct {
1765+
Name string `validate:"required"`
1766+
Age int `validate:"required_if:Name,lee"`
1767+
}
1768+
1769+
u := &user{Name: "lee"}
1770+
v := validate.Struct(u)
1771+
1772+
assert.False(t, v.Validate())
1773+
fmt.Println(v.Errors) // all error messages
1774+
fmt.Println(v.Errors.One()) // returns a random error message text
1775+
fmt.Println(v.Errors.OneError()) // returns a random error
1776+
fmt.Println(v.Errors.Field("Age")) // returns error messages of the field
1777+
}

validators.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -462,11 +462,19 @@ func IsEmpty(val any) bool {
462462
if val == nil {
463463
return true
464464
}
465-
466465
if s, ok := val.(string); ok {
467466
return s == ""
468467
}
469-
return ValueIsEmpty(reflect.ValueOf(val))
468+
469+
var rv reflect.Value
470+
471+
// type check val is reflect.Value
472+
if v2, ok := val.(reflect.Value); ok {
473+
rv = v2
474+
} else {
475+
rv = reflect.ValueOf(val)
476+
}
477+
return ValueIsEmpty(rv)
470478
}
471479

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

0 commit comments

Comments
 (0)