refactor: clean up form binding & validation (#38873)

Clarify the "validation" and "error display" logic.

All the copied&pasted `Validate` functions are removed.
This commit is contained in:
wxiaoguang
2026-08-14 10:15:33 +08:00
committed by GitHub
parent 8b40df255b
commit 72a9debaff
30 changed files with 331 additions and 737 deletions
+28
View File
@@ -0,0 +1,28 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package structs
import (
"net/http"
"gitea.dev/modules/reqctx"
"gitea.dev/modules/translation/i18n"
"gitea.com/go-chi/binding"
)
// ValidateContext is a special context for form validation middleware
type ValidateContext struct {
Locale i18n.LocaleTranslation
Data reqctx.ContextData
Req *http.Request
Resp http.ResponseWriter
}
type FormDefaultValidator struct{}
func (FormDefaultValidator) Validate(ctx *ValidateContext, errs binding.Errors) binding.Errors {
// this default validator only needs to return the errs as is because the "binding" function has already validated
return errs
}
+1
View File
@@ -21,6 +21,7 @@ type SearchError struct {
// MarkupOption markup options
type MarkupOption struct {
FormDefaultValidator
// Text markup to render
//
// in: body
+13 -1
View File
@@ -19,6 +19,18 @@ type Locale interface {
HasKey(trKey string) bool
}
// LocaleTranslation represents an interface to translation
type LocaleTranslation interface {
Language() string
HasKey(trKey string) bool
TrString(string, ...any) string
Tr(key string, args ...any) template.HTML
TrN(cnt any, key1, keyN string, args ...any) template.HTML
PrettyNumber(v any) string
}
// LocaleStore provides the functions common to all locale stores
type LocaleStore interface {
io.Closer
@@ -31,7 +43,7 @@ type LocaleStore interface {
Locale(langName string) (Locale, bool)
// HasLang returns whether a given language is present in the store
HasLang(langName string) bool
// AddLocaleByIni adds a new language to the store
// AddLocaleByJSON adds a new language to the store
AddLocaleByJSON(langName, langDesc string, source, moreSource []byte) error
}
+4
View File
@@ -14,6 +14,10 @@ type MockLocale struct {
Lang, LangName string // these fields are used directly in templates: ctx.Locale.Lang
}
func (l MockLocale) HasKey(trKey string) bool {
return true
}
var _ Locale = (*MockLocale)(nil)
func (l MockLocale) Language() string {
+1 -10
View File
@@ -25,16 +25,7 @@ type contextKey struct{}
var ContextKey any = &contextKey{}
// Locale represents an interface to translation
type Locale interface {
Language() string
TrString(string, ...any) string
Tr(key string, args ...any) template.HTML
TrN(cnt any, key1, keyN string, args ...any) template.HTML
PrettyNumber(v any) string
}
type Locale = i18n.LocaleTranslation
// LangType represents a lang type
type LangType struct {
+1 -7
View File
@@ -37,13 +37,7 @@ func performValidationTest(t *testing.T, testCase validationTestCase) {
m := chi.NewRouter()
m.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) {
actual := binding.Validate(req, testCase.data)
// see https://github.com/stretchr/testify/issues/435
if actual == nil {
actual = binding.Errors{}
}
assert.Equal(t, testCase.expectedErrors, actual)
assert.Equal(t, testCase.expectedErrors, binding.Validate(req, testCase.data))
})
req, err := http.NewRequest(http.MethodPost, testRoute, nil)
-2
View File
@@ -29,14 +29,12 @@ func Test_GlobPatternValidation(t *testing.T) {
data: TestForm{
GlobPattern: "",
},
expectedErrors: binding.Errors{},
},
{
description: "Valid glob",
data: TestForm{
GlobPattern: "{master,release*}",
},
expectedErrors: binding.Errors{},
},
{
-3
View File
@@ -17,21 +17,18 @@ func Test_GitRefNameValidation(t *testing.T) {
data: TestForm{
BranchName: "test",
},
expectedErrors: binding.Errors{},
},
{
description: "Reference name contains single slash",
data: TestForm{
BranchName: "feature/test",
},
expectedErrors: binding.Errors{},
},
{
description: "Reference name has allowed special characters",
data: TestForm{
BranchName: "debian/1%1.6.0-2",
},
expectedErrors: binding.Errors{},
},
{
description: "Reference name contains backslash",
-2
View File
@@ -26,14 +26,12 @@ func Test_RegexPatternValidation(t *testing.T) {
data: TestForm{
RegexPattern: "",
},
expectedErrors: binding.Errors{},
},
{
description: "Valid regex",
data: TestForm{
RegexPattern: `(\d{1,3})+`,
},
expectedErrors: binding.Errors{},
},
{
-5
View File
@@ -18,35 +18,30 @@ func Test_ValidURLValidation(t *testing.T) {
data: TestForm{
URL: "",
},
expectedErrors: binding.Errors{},
},
{
description: "URL without port",
data: TestForm{
URL: "http://test.lan/",
},
expectedErrors: binding.Errors{},
},
{
description: "URL with port",
data: TestForm{
URL: "http://test.lan:3000/",
},
expectedErrors: binding.Errors{},
},
{
description: "URL with IPv6 address without port",
data: TestForm{
URL: "http://[::1]/",
},
expectedErrors: binding.Errors{},
},
{
description: "URL with IPv6 address with port",
data: TestForm{
URL: "http://[::1]:3000/",
},
expectedErrors: binding.Errors{},
},
{
description: "Invalid URL",
+20 -46
View File
@@ -5,12 +5,11 @@
package middleware
import (
"net/http"
"reflect"
"strings"
"gitea.dev/modules/reqctx"
"gitea.dev/modules/setting"
"gitea.dev/modules/structs"
"gitea.dev/modules/translation"
"gitea.dev/modules/util"
"gitea.dev/modules/validation"
@@ -18,17 +17,13 @@ import (
"gitea.com/go-chi/binding"
)
// ValidateContext is a special context for form validation middleware. It may be different from other contexts.
type ValidateContext struct {
Locale translation.Locale
Data reqctx.ContextData
Req *http.Request
Resp http.ResponseWriter
}
type (
ValidateContext = structs.ValidateContext
FormDefaultValidator = structs.FormDefaultValidator
)
// Form form binding interface
type Form interface {
binding.Validator
Validate(ctx *ValidateContext, errs binding.Errors) binding.Errors
}
func init() {
@@ -84,9 +79,17 @@ func getFieldDisplayNameForMessage(f Form, l translation.Locale, fieldNames []st
typ = typ.Elem()
}
field, fieldExists := typ.FieldByName(fieldNames[0])
fieldName := fieldNames[0]
field, fieldExists := typ.FieldByName(fieldName)
if !fieldExists {
return field, false, ""
for tryField := range typ.Fields() {
if util.ToSnakeCase(tryField.Name) == fieldName || tryField.Tag.Get("form") == fieldName {
field, fieldExists = tryField, true
}
}
if !fieldExists {
return field, false, ""
}
}
if field.Tag.Get("form") == "-" {
@@ -95,8 +98,9 @@ func getFieldDisplayNameForMessage(f Form, l translation.Locale, fieldNames []st
trKeyFallback := "form." + field.Name
trKey := util.IfZero(field.Tag.Get("locale"), trKeyFallback)
displayName = l.TrString(trKey)
if displayName == trKeyFallback {
if l.HasKey(trKey) {
displayName = l.TrString(trKey)
} else {
displayName = field.Name
}
return field, true, displayName
@@ -156,7 +160,7 @@ func BuildValidationErrorForUser(f Form, l translation.Locale, bindingErrs bindi
case validation.ErrInvalidBadgeSlug:
errorMessage = l.TrString("form.invalid_slug_error", fieldDisplayName)
default:
setting.PanicInDevOrTesting("unknown binding error classification: %v", classification)
setting.PanicInDevOrTesting("unknown binding error classification for field %T.%s: %v, err: %s", f, errorFieldName, classification, bindingErrMsg)
var msg string
if classification != "" && bindingErrMsg != "" {
msg = classification + ": " + bindingErrMsg
@@ -171,33 +175,3 @@ func BuildValidationErrorForUser(f Form, l translation.Locale, bindingErrs bindi
}
return errorMessage, errorFieldName, fieldNames
}
type contextKeySkipTmplFormValidationErrorType struct{}
var contextKeySkipTmplFormValidationError contextKeySkipTmplFormValidationErrorType
func SkipTmplFormValidationError(ctx reqctx.RequestContext) {
ctx.SetContextValue(contextKeySkipTmplFormValidationError, true)
}
func Validate(ctx *ValidateContext, errs binding.Errors, f Form) binding.Errors {
if ctx.Req.Context().Value(contextKeySkipTmplFormValidationError) == true {
// if it is not using tmpl-based validation error handling, just return the errors
// for example: when using "form-fetch-action", the validation error can be handled by GetFetchActionForm
return errs
}
errorMessage, errorFieldName, _ := BuildValidationErrorForUser(f, ctx.Locale, errs)
if errorMessage == "" {
return errs
}
// Legacy template error handling: try to restore the form's values as much as possible,
// especially for RenderWithErrDeprecated to re-render the form with errors.
AssignForm(f, ctx.Data)
ctx.Data["HasError"] = true
ctx.Data["ErrorMsg"] = errorMessage
if errorFieldName != "" {
ctx.Data["Err_"+errorFieldName] = true
}
return errs
}
+2 -3
View File
@@ -15,17 +15,16 @@ import (
)
type testRangeForm struct {
FormDefaultValidator
Hours int `binding:"Range(0,1000)"`
}
func (f *testRangeForm) Validate(_ *http.Request, errs binding.Errors) binding.Errors { return errs }
func TestBuildValidationErrorForUser(t *testing.T) {
// an out-of-range value must reach its own message instead of the panicking "default" branch
form := &testRangeForm{Hours: 2000}
errs := binding.Validate(httptest.NewRequest(http.MethodPost, "/", nil), form)
errorMessage, errorFieldName, fieldNames := BuildValidationErrorForUser(form, translation.MockLocale{}, errs)
assert.Equal(t, "form.range_error:Hours,0,1000", errorMessage)
assert.Equal(t, "form.range_error:form.Hours,0,1000", errorMessage)
assert.Equal(t, "Hours", errorFieldName)
assert.Equal(t, []string{"Hours"}, fieldNames)
}
+28 -7
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/modules/public"
"gitea.dev/modules/reqctx"
"gitea.dev/modules/setting"
"gitea.dev/modules/translation"
"gitea.dev/modules/web/middleware"
"gitea.dev/modules/web/types"
@@ -21,14 +22,34 @@ import (
"github.com/go-chi/chi/v5"
)
// Bind binding an obj to a handler's context data
func Bind[T any](_ T) http.HandlerFunc {
// Bind binding the request form to a form object and assign context data
func Bind[T interface {
*E
middleware.Form
}, E any]() http.HandlerFunc {
return func(resp http.ResponseWriter, req *http.Request) {
theObj := new(T) // create a new form obj for every request but not use obj directly
data := middleware.GetContextData(req.Context())
_ = binding.Bind(req, theObj) // no need to handle "errs" here, the errors are handled in our middleware.Validate (binding.go)
SetForm(data, theObj)
middleware.AssignForm(theObj, data)
ctx := reqctx.FromContext(req.Context())
data := ctx.GetData()
locale := ctx.Value(translation.ContextKey).(translation.Locale) //nolint:forcetypeassert // must exist
obj := new(E)
var form T = obj
vctx := &middleware.ValidateContext{Locale: locale, Data: data, Req: req, Resp: resp}
errs := binding.Bind(req, obj)
errs = form.Validate(vctx, errs)
SetForm(data, obj)
// Legacy template error handling: try to restore the form's values as much as possible,
// especially for RenderWithErrDeprecated to re-render the form with errors.
middleware.AssignForm(obj, data)
errorMessage, errorFieldName, _ := middleware.BuildValidationErrorForUser(form, locale, errs)
if errorMessage != "" {
data["HasError"] = true
data["ErrorMsg"] = errorMessage
if errorFieldName != "" {
data["Err_"+errorFieldName] = true
}
}
}
}