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

Correction of logic for determining empty value #25

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
27 changes: 10 additions & 17 deletions basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
3 changes: 1 addition & 2 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)}),
)
Expand Down
Loading