From 0ce56d3d7fc433e769db0f261826c5d093fe0283 Mon Sep 17 00:00:00 2001 From: ahmadsaeedgoda Date: Tue, 3 Sep 2024 04:11:50 +0300 Subject: [PATCH] fix: Set default value for form fields - 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? #4042, #13042df, #a41721a --- binding/form_mapping.go | 3 +++ binding/form_mapping_test.go | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/binding/form_mapping.go b/binding/form_mapping.go index 4a35866da2..a84536f722 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -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 diff --git a/binding/form_mapping_test.go b/binding/form_mapping_test.go index c6db033eee..674b5a2d23 100644 --- a/binding/form_mapping_test.go +++ b/binding/form_mapping_test.go @@ -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"`