Skip to content

Commit

Permalink
feat: Add support for omitting empty and zero values in validation
Browse files Browse the repository at this point in the history
  • Loading branch information
zeewell authored and Zeewell.Yu committed Dec 19, 2024
1 parent 6c3307e commit f9b1333
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
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 @@ -1796,6 +1797,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

0 comments on commit f9b1333

Please sign in to comment.