From 8876e2d276515d850a840523adfec896c11cf545 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=9C=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=BA=D0=BE=D0=B2?= Date: Tue, 10 Sep 2024 14:17:29 +0300 Subject: [PATCH] Correction of logic for determining empty value --- basic.go | 27 ++++++++++----------------- validator_test.go | 3 +-- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/basic.go b/basic.go index c8bab8a..7c3f36b 100644 --- a/basic.go +++ b/basic.go @@ -21,29 +21,22 @@ func indirectValue(v any) (value any, isValid bool) { } func valueIsEmpty(value reflect.Value) bool { - if !value.IsValid() || value.IsZero() { + if !value.IsValid() { return true } - kind := value.Kind() - switch kind { + switch value.Kind() { + case reflect.Slice, reflect.Map: + return value.IsNil() || value.Len() == 0 + case reflect.Array, reflect.Struct: + return value.IsZero() case reflect.String: - if len(strings.TrimSpace(value.String())) == 0 { - return true - } - case reflect.Slice: - if value.Len() == 0 { - return true - } + return len(strings.TrimSpace(value.String())) == 0 case reflect.Ptr: - if value.IsNil() { - return true - } - - return valueIsEmpty(value.Elem()) + return value.IsNil() || valueIsEmpty(value.Elem()) + default: + return false } - - return false } func toString(v any) (string, bool) { diff --git a/validator_test.go b/validator_test.go index 03e528e..047fdb6 100644 --- a/validator_test.go +++ b/validator_test.go @@ -27,12 +27,11 @@ func TestValidateValue_Int_Failure(t *testing.T) { err := ValidateValue(ctx, 0, rules...) assert.Error(t, err) - assert.Equal(t, "Value cannot be blank. Value must be no less than 1.", err.Error()) + assert.Equal(t, "Value must be no less than 1.", err.Error()) assert.ErrorAs(t, err, &Result{}) expectedResult := NewResult(). WithError( - NewValidationError("Value cannot be blank."), NewValidationError("Value must be no less than 1."). WithParams(map[string]any{"min": int64(1), "max": int64(3)}), )