From e2e2fb1a1d06943ad6e1f8e4377f90bea2ca7e22 Mon Sep 17 00:00:00 2001 From: SystemGlitch Date: Fri, 15 Nov 2024 16:40:08 +0100 Subject: [PATCH] Validation: fix distinct fail if array is empty --- validation/distinct.go | 5 +++++ validation/distinct_test.go | 1 + 2 files changed, 6 insertions(+) diff --git a/validation/distinct.go b/validation/distinct.go index fdc4b6c8..d369ac38 100644 --- a/validation/distinct.go +++ b/validation/distinct.go @@ -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 diff --git a/validation/distinct_test.go b/validation/distinct_test.go index a4580ee1..a2ccd0c2 100644 --- a/validation/distinct_test.go +++ b/validation/distinct_test.go @@ -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},