Skip to content

Commit

Permalink
Validation: fix distinct fail if array is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
System-Glitch committed Nov 15, 2024
1 parent 6cfc6ad commit e2e2fb1
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
5 changes: 5 additions & 0 deletions validation/distinct.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ type DistinctValidator[T comparable] struct {

// Validate checks the field under validation satisfies this validator's criteria.
func (v *DistinctValidator[T]) Validate(ctx *Context) bool {
if empty, ok := ctx.Value.([]any); ok && len(empty) == 0 {
// The array will stay `[]any` even after recursive validation if it's empty.
// We don't want to check distinct elements for empty arrays.
return true
}
list, ok := ctx.Value.([]T)
if !ok {
return false
Expand Down
1 change: 1 addition & 0 deletions validation/distinct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func TestDistinctValidator(t *testing.T) {
validator Validator
want bool
}{
{value: []any{}, validator: Distinct[string](), want: true},
{value: []string{}, validator: Distinct[string](), want: true},
{value: []string{"a", "b"}, validator: Distinct[string](), want: true},
{value: []string{"a", "b", "a"}, validator: Distinct[string](), want: false},
Expand Down

0 comments on commit e2e2fb1

Please sign in to comment.