Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Required Any Kind of Slice #32

Merged
merged 3 commits into from
Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
language: go
go:
- 1.11.x
- 1.14.x
go_import_path: github.com/teamwork/validate
notifications:
email: false
Expand Down
34 changes: 17 additions & 17 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,31 +239,31 @@ func (v *Validator) Required(key string, value interface{}, message ...string) {
if len(val) == 0 {
v.Append(key, msg)
}
case []string:
if len(val) == 0 {
v.Append(key, msg)
default:
vv := reflect.ValueOf(value)
if vv.Kind() == reflect.Ptr {
if value == reflect.Zero(vv.Type()).Interface() {
v.Append(key, msg)
}
return
}

// Make sure there is at least one non-empty entry.
nonEmpty := false
for i := range val {
if val[i] != "" { // Consider " " to be non-empty on purpose.
nonEmpty = true
break
if vv.Kind() == reflect.Slice {
if vv.Len() == 0 {
v.Append(key, msg)
return
}
}

if !nonEmpty {
v.Append(key, msg)
}
default:
if vv := reflect.ValueOf(value); vv.Kind() == reflect.Ptr {
if value == reflect.Zero(vv.Type()).Interface() {
v.Append(key, msg)
for i := 0; i < vv.Len(); i++ {
if !vv.Index(i).IsZero() && !(vv.Kind() == reflect.Ptr && vv.Index(i).IsNil()) {
return
}
}

v.Append(key, msg)
return
}

panic(fmt.Sprintf("validate: not a supported type: %T", value))
}
}
Expand Down
26 changes: 26 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,32 @@ func TestRequiredString(t *testing.T) {
}
}

func TestRequiredSlice(t *testing.T) {
tests := []struct {
a interface{}
want bool
cesartw marked this conversation as resolved.
Show resolved Hide resolved
}{
{[]struct{}{}, true},
{[]struct{}{{}}, true},
{[]*struct{}{nil}, true},
{[]*struct{}{nil, {}}, false},
{[]string{}, true},
{[]string{""}, true},
{[]string{"text"}, false},
}

for i, tt := range tests {
name := fmt.Sprintf("%v", i)
t.Run(name, func(t *testing.T) {
v := New()
v.Required(name, tt.a)
if got := v.HasErrors(); got != tt.want {
t.Errorf("\ngot: %#v\nwant: %#v\n", got, tt.want)
}
})
}
}

func TestRequiredPtr(t *testing.T) {
type customStruct struct {
String string
Expand Down