Skip to content
Myr

fix(form): Set default value for form fields (#4047)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- 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.

authored by Ahmad Saeed Goda · committed by GitHub · parent 3cb3067 · Browse files · 2 files+23 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Fixes: How to apply default value if empty value provided by client during model binding? #4042, #13042df, #a41721a

Diff stats

2 files+23 added−0 removed

  • other:+23 added−0 removed

2 files+23 added−0 removed

modified:binding/form_mapping_test.go+20 added
67 unmodified lines
68}6970func TestMappingDefault(t *testing.T) {71 var s struct {72 Str string `form:",default=defaultVal"`73 Int int `form:",default=9"`74 Slice []int `form:",default=9"`75 Array [1]int `form:",default=9"`76 }77 err := mappingByPtr(&s, formSource{}, "form")78 require.NoError(t, err)7980 assert.Equal(t, "defaultVal", s.Str)81 assert.Equal(t, 9, s.Int)82 assert.Equal(t, []int{9}, s.Slice)83 assert.Equal(t, [1]int{9}, s.Array)84}
68 unmodified lines
153 require.NoError(t, err)154 assert.Equal(t, 6, s.F)155}156157func 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}165166func 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}174175func TestMapFormWithTag(t *testing.T) {176 var s struct {177 F int `externalTag:"field"`178 }
393 unmodified lines
modified:binding/form_mapping.go+3 added
259 unmodified lines
260 }261262 if len(vs) > 0 {263 val = vs[0]264 if val == "" {265 val = opt.defaultValue266 }267 }268 if ok, err := trySetCustom(val, value); ok {269 return ok, err270 }
212 unmodified lines