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