Skip to content

Commit

Permalink
feat: add required_if_contains and excluded_if_contains
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasoares committed Apr 25, 2024
1 parent a0f74b0 commit 58330a7
Show file tree
Hide file tree
Showing 5 changed files with 224 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -244,12 +244,14 @@ validate := validator.New(validator.WithRequiredStructEnabled())
| oneof | One Of |
| required | Required |
| required_if | Required If |
| required_if_contains | Required If Contains |
| required_unless | Required Unless |
| required_with | Required With |
| required_with_all | Required With All |
| required_without | Required Without |
| required_without_all | Required Without All |
| excluded_if | Excluded If |
| excluded_if_contains | Excluded If Contains |
| excluded_unless | Excluded Unless |
| excluded_with | Excluded With |
| excluded_with_all | Excluded With All |
Expand Down
64 changes: 64 additions & 0 deletions baked_in.go
Expand Up @@ -74,13 +74,15 @@ var (
bakedInValidators = map[string]Func{
"required": hasValue,
"required_if": requiredIf,
"required_if_contains": requiredIfContains,
"required_unless": requiredUnless,
"skip_unless": skipUnless,
"required_with": requiredWith,
"required_with_all": requiredWithAll,
"required_without": requiredWithout,
"required_without_all": requiredWithoutAll,
"excluded_if": excludedIf,
"excluded_if_contains": excludedIfContains,
"excluded_unless": excludedUnless,
"excluded_with": excludedWith,
"excluded_with_all": excludedWithAll,
Expand Down Expand Up @@ -1792,12 +1794,23 @@ func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue boo
// requireCheckFieldValue is a func for check field value
func requireCheckFieldValue(
fl FieldLevel, param string, value string, defaultNotFoundValue bool,
) bool {
return requireCheckFieldValues(fl, param, value, defaultNotFoundValue, false)
}

// requireCheckFieldValue is a func for check field value
func requireCheckFieldValues(
fl FieldLevel, param string, value string, defaultNotFoundValue bool, sliceContains bool,
) bool {
field, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), param)
if !found {
return defaultNotFoundValue
}

return compareValues(field, kind, value, sliceContains)
}

func compareValues(field reflect.Value, kind reflect.Kind, value string, sliceContains bool) bool {
switch kind {

case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
Expand All @@ -1813,8 +1826,28 @@ func requireCheckFieldValue(
return field.Float() == asFloat64(value)

case reflect.Slice, reflect.Map, reflect.Array:
// If slice contains is true, should look for the value inside the slice
if sliceContains {
for i := 0; i < field.Len(); i++ {
item := field.Index(i)
if compareValues(item, item.Kind(), value, false) {
return true
}
}

return false
}

return int64(field.Len()) == asInt(value)

case reflect.Ptr:
if field.IsNil() {
return false
}

element := field.Elem()

return compareValues(element, element.Kind(), value, false)
case reflect.Bool:
return field.Bool() == asBool(value)
}
Expand All @@ -1838,6 +1871,21 @@ func requiredIf(fl FieldLevel) bool {
return hasValue(fl)
}

// requiredIfContains is the validation function
// The field under validation must be present and not empty only if all the other specified fields are equal to the value following with the specified field.
func requiredIfContains(fl FieldLevel) bool {
params := parseOneOfParam2(fl.Param())
if len(params)%2 != 0 {
panic(fmt.Sprintf("Bad param number for required_if_contains %s", fl.FieldName()))
}
for i := 0; i < len(params); i += 2 {
if !requireCheckFieldValues(fl, params[i], params[i+1], false, true) {
return true
}
}
return hasValue(fl)
}

// excludedIf is the validation function
// The field under validation must not be present or is empty only if all the other specified fields are equal to the value following with the specified field.
func excludedIf(fl FieldLevel) bool {
Expand All @@ -1854,6 +1902,22 @@ func excludedIf(fl FieldLevel) bool {
return !hasValue(fl)
}

// excludedIfContains is the validation function
// The field under validation must not be present or is empty only if all the other specified fields are equal to the value following with the specified field.
func excludedIfContains(fl FieldLevel) bool {
params := parseOneOfParam2(fl.Param())
if len(params)%2 != 0 {
panic(fmt.Sprintf("Bad param number for excluded_if_contains %s", fl.FieldName()))
}

for i := 0; i < len(params); i += 2 {
if !requireCheckFieldValues(fl, params[i], params[i+1], false, true) {
return true
}
}
return !hasValue(fl)
}

// requiredUnless is the validation function
// The field under validation must be present and not empty only unless all the other specified fields are equal to the value following with the specified field.
func requiredUnless(fl FieldLevel) bool {
Expand Down
38 changes: 38 additions & 0 deletions doc.go
Expand Up @@ -275,6 +275,25 @@ Examples:
// require the field if the Field1 and Field2 is equal to the value respectively:
Usage: required_if=Field1 foo Field2 bar
# Required If Contains
The field under validation must be present and not empty only if all
the other specified fields are equal to the value following the specified
field. For strings ensures value is not "". For slices, maps, pointers,
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
Diferent from required_if, this tag will dive into slices to check if the value is present instead of checking the slice size.
Usage: required_if_contains
Examples:
// require the field if the Field1 contains the parameter given:
Usage: required_if_contains=Field1 foobar
// require the field if the Field1 and Field2 contains the value respectively:
Usage: required_if_contains=Field1 foo Field2 bar
# Required Unless
The field under validation must be present and not empty unless all
Expand Down Expand Up @@ -371,6 +390,25 @@ Examples:
// exclude the field if the Field1 and Field2 is equal to the value respectively:
Usage: excluded_if=Field1 foo Field2 bar
# Excluded If Contains
The field under validation must not be present or not empty only if all
the other specified fields are equal to the value following the specified
field. For strings ensures value is not "". For slices, maps, pointers,
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
Diferent from excluded_if, this tag will dive into slices to check if the value is present instead of checking the slice size.
Usage: excluded_if_contains
Examples:
// exclude the field if the Field1 contains the parameter given:
Usage: excluded_if_contains=Field1 foobar
// exclude the field if the Field1 and Field2 contains the value respectively:
Usage: excluded_if_contains=Field1 foo Field2 bar
# Excluded Unless
The field under validation must not be present or empty unless all
Expand Down
6 changes: 4 additions & 2 deletions validator_instance.go
Expand Up @@ -29,13 +29,15 @@ const (
requiredWithTag = "required_with"
requiredWithAllTag = "required_with_all"
requiredIfTag = "required_if"
requiredIfContainsTag = "required_if_contains"
requiredUnlessTag = "required_unless"
skipUnlessTag = "skip_unless"
excludedWithoutAllTag = "excluded_without_all"
excludedWithoutTag = "excluded_without"
excludedWithTag = "excluded_with"
excludedWithAllTag = "excluded_with_all"
excludedIfTag = "excluded_if"
excludedIfContainsTag = "excluded_if_contains"
excludedUnlessTag = "excluded_unless"
skipValidationTag = "-"
diveTag = "dive"
Expand Down Expand Up @@ -128,8 +130,8 @@ func New(options ...Option) *Validate {

switch k {
// these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour
case requiredIfTag, requiredUnlessTag, requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag,
excludedIfTag, excludedUnlessTag, excludedWithTag, excludedWithAllTag, excludedWithoutTag, excludedWithoutAllTag,
case requiredIfContainsTag, requiredIfTag, requiredUnlessTag, requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag,
excludedIfContainsTag, excludedIfTag, excludedUnlessTag, excludedWithTag, excludedWithAllTag, excludedWithoutTag, excludedWithoutAllTag,
skipUnlessTag:
_ = v.registerValidation(k, wrapFunc(val), true, true)
default:
Expand Down
116 changes: 116 additions & 0 deletions validator_test.go
Expand Up @@ -13794,3 +13794,119 @@ func TestPrivateFieldsStruct(t *testing.T) {
Equal(t, len(errs), tc.errorNum)
}
}

func TestRequiredIfContains(t *testing.T) {
type Inner struct {
Field []string
}

fieldVal := "test"
fieldValInt := 1
type test struct {
InnerP *Inner
Inner Inner
FieldS []string `validate:"omitempty" json:"field_e"`
FieldI []int `validate:"omitempty" json:"field_i"`
FieldIP []*int `validate:"omitempty" json:"field_ip"`
FieldTS string `validate:"required_if_contains=FieldS test" json:"field_ts"`
FieldTI string `validate:"required_if_contains=FieldI 1" json:"field_ti"`
FieldTIP string `validate:"required_if_contains=FieldIP 1" json:"field_tip"`
FieldTInnerP string `validate:"required_if_contains=InnerP.Field test" json:"field_t_innerp"`
FieldTInner string `validate:"required_if_contains=Inner.Field test" json:"field_t_inner"`
}

validationOk := test{
InnerP: &Inner{Field: []string{fieldVal}},
Inner: Inner{Field: []string{fieldVal}},
FieldS: []string{fieldVal},
FieldI: []int{1},
FieldTS: fieldVal,
FieldTI: fieldVal,
FieldTIP: fieldVal,
FieldTInnerP: fieldVal,
FieldTInner: fieldVal,
}

validate := New()

errs := validate.Struct(validationOk)
Equal(t, errs, nil)

validationNotOk := test{
InnerP: &Inner{Field: []string{fieldVal}},
Inner: Inner{Field: []string{fieldVal}},
FieldS: []string{fieldVal},
FieldI: []int{1},
FieldIP: []*int{&fieldValInt},
}

errs = validate.Struct(validationNotOk)
NotEqual(t, errs, nil)

ve := errs.(ValidationErrors)
Equal(t, len(ve), 5)

AssertError(t, errs, "test.FieldTS", "test.FieldTS", "FieldTS", "FieldTS", "required_if_contains")
AssertError(t, errs, "test.FieldTI", "test.FieldTI", "FieldTI", "FieldTI", "required_if_contains")
AssertError(t, errs, "test.FieldTIP", "test.FieldTIP", "FieldTIP", "FieldTIP", "required_if_contains")
AssertError(t, errs, "test.FieldTInnerP", "test.FieldTInnerP", "FieldTInnerP", "FieldTInnerP", "required_if_contains")
AssertError(t, errs, "test.FieldTInner", "test.FieldTInner", "FieldTInner", "FieldTInner", "required_if_contains")
}

func TestExcludeIfContains(t *testing.T) {
type Inner struct {
Field []string
}

fieldVal := "test"
fieldValInt := 1
type test struct {
InnerP *Inner
Inner Inner
FieldS []string `validate:"omitempty" json:"field_e"`
FieldI []int `validate:"omitempty" json:"field_i"`
FieldIP []*int `validate:"omitempty" json:"field_ip"`
FieldTS string `validate:"excluded_if_contains=FieldS test" json:"field_ts"`
FieldTI string `validate:"excluded_if_contains=FieldI 1" json:"field_ti"`
FieldTIP string `validate:"excluded_if_contains=FieldIP 1" json:"field_tip"`
FieldTInnerP string `validate:"excluded_if_contains=InnerP.Field test" json:"field_t_innerp"`
FieldTInner string `validate:"excluded_if_contains=Inner.Field test" json:"field_t_inner"`
}

validationOk := test{
InnerP: &Inner{Field: []string{fieldVal}},
Inner: Inner{Field: []string{fieldVal}},
FieldS: []string{fieldVal},
FieldI: []int{1},
}

validate := New()

errs := validate.Struct(validationOk)
Equal(t, errs, nil)

validationNotOk := test{
InnerP: &Inner{Field: []string{fieldVal}},
Inner: Inner{Field: []string{fieldVal}},
FieldS: []string{fieldVal},
FieldI: []int{1},
FieldIP: []*int{&fieldValInt},
FieldTS: fieldVal,
FieldTI: fieldVal,
FieldTIP: fieldVal,
FieldTInnerP: fieldVal,
FieldTInner: fieldVal,
}

errs = validate.Struct(validationNotOk)
NotEqual(t, errs, nil)

ve := errs.(ValidationErrors)
Equal(t, len(ve), 5)

AssertError(t, errs, "test.FieldTS", "test.FieldTS", "FieldTS", "FieldTS", "excluded_if_contains")
AssertError(t, errs, "test.FieldTI", "test.FieldTI", "FieldTI", "FieldTI", "excluded_if_contains")
AssertError(t, errs, "test.FieldTIP", "test.FieldTIP", "FieldTIP", "FieldTIP", "excluded_if_contains")
AssertError(t, errs, "test.FieldTInnerP", "test.FieldTInnerP", "FieldTInnerP", "FieldTInnerP", "excluded_if_contains")
AssertError(t, errs, "test.FieldTInner", "test.FieldTInner", "FieldTInner", "FieldTInner", "excluded_if_contains")
}

0 comments on commit 58330a7

Please sign in to comment.