Skip to content

Commit

Permalink
Merge pull request #183 from OscarVanL/fix/json-tag-field-name-parsing
Browse files Browse the repository at this point in the history
Fix #182
  • Loading branch information
inhere authored Nov 22, 2022
2 parents 5d642e4 + 42d952c commit 97f1366
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ func (d *StructData) parseRulesFromTag(v *Validation) {
outName := ""
if gOpt.FieldTag != "" {
outName = fv.Tag.Get(gOpt.FieldTag)
outName = strings.SplitN(outName, ",", 2)[0]
}

// add pre field display name to fName
Expand Down
34 changes: 34 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,37 @@ func TestStruct_create_error(t *testing.T) {
assert.Equal(t, "invalid input data", v.Errors.One())
assert.False(t, v.Validate())
}

func TestStruct_json_tag_name_parsing(t *testing.T) {
// Ensure that the JSON tag after comma is ignored.
type Thing struct {
Field string `json:"test,omitempty" validate:"email"`
}

th := Thing{Field: "a"}

v := Struct(th)
assert.False(t, v.Validate())

dump.Println(v.Errors)
assert.True(t, v.Errors.HasField("test"))

errStr := v.Errors["test"]["email"]
assert.True(t, strings.HasPrefix(errStr, "test "))

// Ensure that the field name is used if the JSON tag name is empty.
type Thing2 struct {
Field string `json:",omitempty" validate:"email"`
}

th2 := Thing2{Field: "a"}

v = Struct(th2)
assert.False(t, v.Validate())

dump.Println(v.Errors)
assert.True(t, v.Errors.HasField("Field"))

errStr = v.Errors["Field"]["email"]
assert.True(t, strings.HasPrefix(errStr, "Field "))
}

0 comments on commit 97f1366

Please sign in to comment.