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

feat: Add support for omitting empty and zero values in validation (including nil pointer and empty content of pointer) #1289

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
15 changes: 15 additions & 0 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ var (
keysTag: {},
endKeysTag: {},
structOnlyTag: {},
omitzero: {},
omitempty: {},
omitnil: {},
skipValidationTag: {},
Expand Down Expand Up @@ -1777,6 +1778,20 @@ func hasValue(fl FieldLevel) bool {
}
}

// hasNotZeroValue is the validation function for validating if the current field's value is not the zero value for its type.
func hasNotZeroValue(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:
return !field.IsNil()
default:
if fl.(*validate).fldIsPointer && field.Interface() != nil {
return !field.IsZero()
}
return field.IsValid() && !field.IsZero()
}
}

// requireCheckFieldKind is a func for check field kind
func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue bool) bool {
field := fl.Field()
Expand Down
5 changes: 5 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const (
typeKeys
typeEndKeys
typeOmitNil
typeOmitZero
)

const (
Expand Down Expand Up @@ -249,6 +250,10 @@ func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias s
}
return

case omitzero:
current.typeof = typeOmitZero
continue

case omitempty:
current.typeof = typeOmitEmpty
continue
Expand Down
17 changes: 17 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr
return
}

if ct.typeof == typeOmitZero {
return
}

if ct.hasTag {
if kind == reflect.Invalid {
v.str1 = string(append(ns, cf.altName...))
Expand Down Expand Up @@ -238,6 +242,19 @@ OUTER:
ct = ct.next
continue

case typeOmitZero:
v.slflParent = parent
v.flField = current
v.cf = cf
v.ct = ct

if !hasNotZeroValue(v) {
return
}

ct = ct.next
continue

case typeOmitNil:
v.slflParent = parent
v.flField = current
Expand Down
1 change: 1 addition & 0 deletions validator_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const (
tagKeySeparator = "="
structOnlyTag = "structonly"
noStructLevelTag = "nostructlevel"
omitzero = "omitzero"
omitempty = "omitempty"
omitnil = "omitnil"
isdefault = "isdefault"
Expand Down
51 changes: 51 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13900,6 +13900,57 @@ func TestOmitNilAndRequired(t *testing.T) {
})
}

func TestOmitZero(t *testing.T) {
type (
OmitEmpty struct {
Str string `validate:"omitempty,min=10"`
StrPtr *string `validate:"omitempty,min=10"`
}
OmitZero struct {
Str string `validate:"omitzero,min=10"`
StrPtr *string `validate:"omitzero,min=10"`
}
)

var (
validate = New()
valid = "this is the long string to pass the validation rule"
empty = ""
)

t.Run("compare using valid data", func(t *testing.T) {
err1 := validate.Struct(OmitEmpty{Str: valid, StrPtr: &valid})
err2 := validate.Struct(OmitZero{Str: valid, StrPtr: &valid})

Equal(t, err1, nil)
Equal(t, err2, nil)
})

t.Run("compare fully empty omitempty and omitzero", func(t *testing.T) {
err1 := validate.Struct(OmitEmpty{})
err2 := validate.Struct(OmitZero{})

Equal(t, err1, nil)
Equal(t, err2, nil)
})

t.Run("compare with zero value", func(t *testing.T) {
err1 := validate.Struct(OmitEmpty{Str: "", StrPtr: nil})
err2 := validate.Struct(OmitZero{Str: "", StrPtr: nil})

Equal(t, err1, nil)
Equal(t, err2, nil)
})

t.Run("compare with empty value", func(t *testing.T) {
err1 := validate.Struct(OmitEmpty{Str: empty, StrPtr: &empty})
err2 := validate.Struct(OmitZero{Str: empty, StrPtr: &empty})

AssertError(t, err1, "OmitEmpty.StrPtr", "OmitEmpty.StrPtr", "StrPtr", "StrPtr", "min")
Equal(t, err2, nil)
})
}

func TestPrivateFieldsStruct(t *testing.T) {
type tc struct {
stct interface{}
Expand Down