Skip to content

Commit

Permalink
Add tests for FieldLevel Name functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Dean Karn committed Jun 12, 2017
1 parent 223722e commit d4768f8
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7013,3 +7013,69 @@ func TestMapStructNamespace(t *testing.T) {
Equal(t, len(ve), 1)
AssertError(t, errs, "children[1].name", "Children[1].Name", "name", "Name", "required")
}

func TestFieldLevelName(t *testing.T) {
type Test struct {
String string `validate:"custom1" json:"json1"`
Array []string `validate:"dive,custom2" json:"json2"`
Map map[string]string `validate:"dive,custom3" json:"json3"`
Array2 []string `validate:"custom4" json:"json4"`
Map2 map[string]string `validate:"custom5" json:"json5"`
}

var res1, res2, res3, res4, res5, alt1, alt2, alt3, alt4, alt5 string
validate := New()
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]

if name == "-" {
return ""
}

return name
})
validate.RegisterValidation("custom1", func(fl FieldLevel) bool {
res1 = fl.FieldName()
alt1 = fl.StructFieldName()
return true
})
validate.RegisterValidation("custom2", func(fl FieldLevel) bool {
res2 = fl.FieldName()
alt2 = fl.StructFieldName()
return true
})
validate.RegisterValidation("custom3", func(fl FieldLevel) bool {
res3 = fl.FieldName()
alt3 = fl.StructFieldName()
return true
})
validate.RegisterValidation("custom4", func(fl FieldLevel) bool {
res4 = fl.FieldName()
alt4 = fl.StructFieldName()
return true
})
validate.RegisterValidation("custom5", func(fl FieldLevel) bool {
res5 = fl.FieldName()
alt5 = fl.StructFieldName()
return true
})

test := Test{
String: "test",
Array: []string{"1"},
Map: map[string]string{"test": "test"},
}

errs := validate.Struct(test)
Equal(t, errs, nil)
Equal(t, res1, "json1")
Equal(t, alt1, "String")
Equal(t, res2, "json2[0]")
Equal(t, alt2, "Array[0]")
Equal(t, res3, "json3[test]")
Equal(t, alt3, "Map[test]")
Equal(t, res4, "json4")
Equal(t, alt4, "Array2")
Equal(t, res5, "json5")
Equal(t, alt5, "Map2")
}

0 comments on commit d4768f8

Please sign in to comment.