Skip to content

Commit

Permalink
fix: Set default value for form fields
Browse files Browse the repository at this point in the history
- Use provided default value in struct tags when binding a request input to struct for validation.

Fixes: How to apply default value if empty value provided by client during model binding? gin-gonic#4042, #13042df, #a41721a
  • Loading branch information
ahmadSaeedGoda committed Sep 3, 2024
1 parent 3cb3067 commit 0ce56d3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
3 changes: 3 additions & 0 deletions binding/form_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][

if len(vs) > 0 {
val = vs[0]
if val == "" {
val = opt.defaultValue
}
}
if ok, err := trySetCustom(val, value); ok {
return ok, err
Expand Down
9 changes: 9 additions & 0 deletions binding/form_mapping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,15 @@ func TestMappingForm(t *testing.T) {
assert.Equal(t, 6, s.F)
}

func TestMappingFormWithEmptyToDefault(t *testing.T) {
var s struct {
F string `form:"field,default=DefVal"`
}
err := mapForm(&s, map[string][]string{"field": {""}})
require.NoError(t, err)
assert.Equal(t, "DefVal", s.F)
}

func TestMapFormWithTag(t *testing.T) {
var s struct {
F int `externalTag:"field"`
Expand Down

0 comments on commit 0ce56d3

Please sign in to comment.