Skip to content

Commit 28e57f5

Browse files
fix(form): Set default value for form fields (#4047)
- Use specified default value in struct tags when binding a request input to struct for validation, even if sent empty, not only when not sent at all. - Add string field to `TestMappingDefault` test case. - Add test case for not sent form field to default to the value specified via code. - Add test case for form field sent empty to default to the value specified via code. Fixes: How to apply default value if empty value provided by client during model binding? #4042, #13042df, #a41721a
1 parent 3cb3067 commit 28e57f5

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

binding/form_mapping.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
261261

262262
if len(vs) > 0 {
263263
val = vs[0]
264+
if val == "" {
265+
val = opt.defaultValue
266+
}
264267
}
265268
if ok, err := trySetCustom(val, value); ok {
266269
return ok, err

binding/form_mapping_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,15 @@ func TestMappingBaseTypes(t *testing.T) {
6969

7070
func TestMappingDefault(t *testing.T) {
7171
var s struct {
72+
Str string `form:",default=defaultVal"`
7273
Int int `form:",default=9"`
7374
Slice []int `form:",default=9"`
7475
Array [1]int `form:",default=9"`
7576
}
7677
err := mappingByPtr(&s, formSource{}, "form")
7778
require.NoError(t, err)
7879

80+
assert.Equal(t, "defaultVal", s.Str)
7981
assert.Equal(t, 9, s.Int)
8082
assert.Equal(t, []int{9}, s.Slice)
8183
assert.Equal(t, [1]int{9}, s.Array)
@@ -152,6 +154,24 @@ func TestMappingForm(t *testing.T) {
152154
assert.Equal(t, 6, s.F)
153155
}
154156

157+
func TestMappingFormFieldNotSent(t *testing.T) {
158+
var s struct {
159+
F string `form:"field,default=defVal"`
160+
}
161+
err := mapForm(&s, map[string][]string{})
162+
require.NoError(t, err)
163+
assert.Equal(t, "defVal", s.F)
164+
}
165+
166+
func TestMappingFormWithEmptyToDefault(t *testing.T) {
167+
var s struct {
168+
F string `form:"field,default=DefVal"`
169+
}
170+
err := mapForm(&s, map[string][]string{"field": {""}})
171+
require.NoError(t, err)
172+
assert.Equal(t, "DefVal", s.F)
173+
}
174+
155175
func TestMapFormWithTag(t *testing.T) {
156176
var s struct {
157177
F int `externalTag:"field"`

0 commit comments

Comments
 (0)