Skip to content

Commit 97f1366

Browse files
authored
Merge pull request #183 from OscarVanL/fix/json-tag-field-name-parsing
Fix #182
2 parents 5d642e4 + 42d952c commit 97f1366

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

data_source.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,7 @@ func (d *StructData) parseRulesFromTag(v *Validation) {
332332
outName := ""
333333
if gOpt.FieldTag != "" {
334334
outName = fv.Tag.Get(gOpt.FieldTag)
335+
outName = strings.SplitN(outName, ",", 2)[0]
335336
}
336337

337338
// add pre field display name to fName

validate_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,3 +240,37 @@ func TestStruct_create_error(t *testing.T) {
240240
assert.Equal(t, "invalid input data", v.Errors.One())
241241
assert.False(t, v.Validate())
242242
}
243+
244+
func TestStruct_json_tag_name_parsing(t *testing.T) {
245+
// Ensure that the JSON tag after comma is ignored.
246+
type Thing struct {
247+
Field string `json:"test,omitempty" validate:"email"`
248+
}
249+
250+
th := Thing{Field: "a"}
251+
252+
v := Struct(th)
253+
assert.False(t, v.Validate())
254+
255+
dump.Println(v.Errors)
256+
assert.True(t, v.Errors.HasField("test"))
257+
258+
errStr := v.Errors["test"]["email"]
259+
assert.True(t, strings.HasPrefix(errStr, "test "))
260+
261+
// Ensure that the field name is used if the JSON tag name is empty.
262+
type Thing2 struct {
263+
Field string `json:",omitempty" validate:"email"`
264+
}
265+
266+
th2 := Thing2{Field: "a"}
267+
268+
v = Struct(th2)
269+
assert.False(t, v.Validate())
270+
271+
dump.Println(v.Errors)
272+
assert.True(t, v.Errors.HasField("Field"))
273+
274+
errStr = v.Errors["Field"]["email"]
275+
assert.True(t, strings.HasPrefix(errStr, "Field "))
276+
}

0 commit comments

Comments
 (0)