mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-11 17:08:45 +00:00
refactor: form binding validation (#38832)
Make "form-fetch-action" highlight the invalid field as "error"
This commit is contained in:
@@ -5,9 +5,12 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/modules/reqctx"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/translation"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/validation"
|
||||
@@ -15,6 +18,14 @@ 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
|
||||
}
|
||||
|
||||
// Form form binding interface
|
||||
type Form interface {
|
||||
binding.Validator
|
||||
@@ -49,7 +60,8 @@ func AssignForm(form any, data map[string]any) {
|
||||
}
|
||||
}
|
||||
|
||||
func getRuleBody(field reflect.StructField, prefix string) string {
|
||||
func getRuleBody(field reflect.StructField, ruleName string) string {
|
||||
prefix := ruleName + "("
|
||||
for rule := range strings.SplitSeq(field.Tag.Get("binding"), ";") {
|
||||
if strings.HasPrefix(rule, prefix) {
|
||||
return rule[len(prefix) : len(rule)-1]
|
||||
@@ -58,117 +70,134 @@ func getRuleBody(field reflect.StructField, prefix string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetSize get size int form tag
|
||||
func GetSize(field reflect.StructField) string {
|
||||
return getRuleBody(field, "Size(")
|
||||
}
|
||||
|
||||
// GetMinSize get minimal size in form tag
|
||||
func GetMinSize(field reflect.StructField) string {
|
||||
return getRuleBody(field, "MinSize(")
|
||||
}
|
||||
|
||||
// GetMaxSize get max size in form tag
|
||||
func GetMaxSize(field reflect.StructField) string {
|
||||
return getRuleBody(field, "MaxSize(")
|
||||
}
|
||||
|
||||
// GetInclude get include in form tag
|
||||
func GetInclude(field reflect.StructField) string {
|
||||
return getRuleBody(field, "Include(")
|
||||
}
|
||||
|
||||
func ReportValidationError(errs binding.Errors, data map[string]any, fieldName, classification, errorMsg string) binding.Errors {
|
||||
errs.Add([]string{fieldName}, classification, errorMsg)
|
||||
|
||||
data["HasError"] = true
|
||||
data["ErrorMsg"] = fieldName + ": " + errorMsg
|
||||
data["Err_"+fieldName] = true
|
||||
// there is already a reported validation error, so no need to generate default error messages in Validate()
|
||||
data["HasErrorFormValidation"] = true
|
||||
func AddValidationError(errs binding.Errors, fieldName, errorMsg string) binding.Errors {
|
||||
errs.Add([]string{fieldName}, validation.ErrCustomMessage, errorMsg)
|
||||
return errs
|
||||
}
|
||||
|
||||
func Validate(errs binding.Errors, data map[string]any, f Form, l translation.Locale) binding.Errors {
|
||||
// try to restore the form's values as much as possible,
|
||||
// especially for RenderWithErrDeprecated to re-render the form with errors
|
||||
AssignForm(f, data)
|
||||
|
||||
if errs.Len() == 0 || data["HasErrorFormValidation"] == true {
|
||||
return errs
|
||||
func getFieldDisplayNameForMessage(f Form, l translation.Locale, fieldNames []string) (field reflect.StructField, ok bool, displayName string) {
|
||||
if len(fieldNames) == 0 {
|
||||
return field, false, ""
|
||||
}
|
||||
|
||||
// if HasError=true, then must set default error message
|
||||
// because still a lot of places use `ctx.Data["ErrorMsg"].(string)` even if the error fields can't be found
|
||||
data["HasError"] = true
|
||||
data["ErrorMsg"] = l.TrString("form.unknown_error")
|
||||
|
||||
typ := reflect.TypeOf(f)
|
||||
if typ.Kind() == reflect.Pointer {
|
||||
typ = typ.Elem()
|
||||
}
|
||||
|
||||
field, fieldExists := typ.FieldByName(errs[0].FieldNames[0])
|
||||
field, fieldExists := typ.FieldByName(fieldNames[0])
|
||||
if !fieldExists {
|
||||
return errs
|
||||
return field, false, ""
|
||||
}
|
||||
|
||||
if field.Tag.Get("form") == "-" {
|
||||
return field, false, ""
|
||||
}
|
||||
|
||||
trKeyFallback := "form." + field.Name
|
||||
trKey := util.IfZero(field.Tag.Get("locale"), trKeyFallback)
|
||||
displayName = l.TrString(trKey)
|
||||
if displayName == trKeyFallback {
|
||||
displayName = field.Name
|
||||
}
|
||||
return field, true, displayName
|
||||
}
|
||||
|
||||
func BuildValidationErrorForUser(f Form, l translation.Locale, bindingErrs binding.Errors) (errorMessage, errorFieldName string, fieldNames []string) {
|
||||
if bindingErrs.Len() == 0 {
|
||||
return "", "", nil
|
||||
}
|
||||
bindingErr := bindingErrs[0]
|
||||
fieldNames, classification, bindingErrMsg := bindingErr.FieldNames, bindingErr.Classification, bindingErr.Message
|
||||
field, ok, fieldDisplayName := getFieldDisplayNameForMessage(f, l, fieldNames)
|
||||
if !ok {
|
||||
return l.TrString("error.occurred"), "", fieldNames
|
||||
}
|
||||
|
||||
errorFieldName = field.Name
|
||||
switch classification {
|
||||
case binding.ERR_REQUIRED:
|
||||
errorMessage = l.TrString("form.require_error", fieldDisplayName)
|
||||
case binding.ERR_ALPHA_DASH:
|
||||
errorMessage = l.TrString("form.alpha_dash_error", fieldDisplayName)
|
||||
case binding.ERR_ALPHA_DASH_DOT:
|
||||
errorMessage = l.TrString("form.alpha_dash_dot_error", fieldDisplayName)
|
||||
case binding.ERR_MIN_SIZE:
|
||||
errorMessage = l.TrString("form.min_size_error", fieldDisplayName, getRuleBody(field, "MinSize"))
|
||||
case binding.ERR_MAX_SIZE:
|
||||
errorMessage = l.TrString("form.max_size_error", fieldDisplayName, getRuleBody(field, "MaxSize"))
|
||||
case binding.ERR_RANGE:
|
||||
rangeMin, rangeMax, _ := strings.Cut(getRuleBody(field, "Range"), ",")
|
||||
errorMessage = l.TrString("form.range_error", fieldDisplayName, rangeMin, rangeMax)
|
||||
case binding.ERR_EMAIL:
|
||||
errorMessage = l.TrString("form.email_error", fieldDisplayName)
|
||||
case binding.ERR_URL:
|
||||
errorMessage = l.TrString("form.url_error", fieldDisplayName)
|
||||
case binding.ERR_IN:
|
||||
ruleBody := getRuleBody(field, "In")
|
||||
if strings.HasPrefix(ruleBody, ",") {
|
||||
ruleBody = "(empty)" + ruleBody
|
||||
}
|
||||
errorMessage = l.TrString("form.in_error", fieldDisplayName, ruleBody)
|
||||
case binding.ERR_INCLUDE:
|
||||
errorMessage = l.TrString("form.include_error", fieldDisplayName, getRuleBody(field, "Include"))
|
||||
|
||||
case validation.ErrCustomMessage:
|
||||
errorMessage = bindingErrMsg
|
||||
case validation.ErrGitRefName:
|
||||
errorMessage = l.TrString("form.git_ref_name_error", fieldDisplayName)
|
||||
case validation.ErrGlobPattern:
|
||||
errorMessage = l.TrString("form.glob_pattern_error", fieldDisplayName, bindingErrMsg)
|
||||
case validation.ErrRegexPattern:
|
||||
errorMessage = l.TrString("form.regex_pattern_error", fieldDisplayName, bindingErrMsg)
|
||||
case validation.ErrUsername:
|
||||
errorMessage = l.TrString("form.username_error", fieldDisplayName)
|
||||
case validation.ErrInvalidGroupTeamMap:
|
||||
errorMessage = l.TrString("form.invalid_group_team_map_error", fieldDisplayName, bindingErrMsg)
|
||||
case validation.ErrInvalidBadgeSlug:
|
||||
errorMessage = l.TrString("form.invalid_slug_error", fieldDisplayName)
|
||||
default:
|
||||
setting.PanicInDevOrTesting("unknown binding error classification: %v", classification)
|
||||
var msg string
|
||||
if classification != "" && bindingErrMsg != "" {
|
||||
msg = classification + ": " + bindingErrMsg
|
||||
} else {
|
||||
msg = util.IfZero(bindingErrMsg, classification)
|
||||
if msg == "" {
|
||||
setting.PanicInDevOrTesting("no error message for binding error: %v", bindingErr)
|
||||
}
|
||||
msg = util.IfZero(msg, "unknown error")
|
||||
}
|
||||
errorMessage = l.TrString("form.field_invalid_message", fieldDisplayName, msg)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
data["Err_"+field.Name] = true
|
||||
|
||||
trName := field.Tag.Get("locale")
|
||||
if len(trName) == 0 {
|
||||
trName = l.TrString("form." + field.Name)
|
||||
} else {
|
||||
trName = l.TrString(trName)
|
||||
// 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
|
||||
}
|
||||
|
||||
switch errs[0].Classification {
|
||||
case binding.ERR_REQUIRED:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.require_error")
|
||||
case binding.ERR_ALPHA_DASH:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.alpha_dash_error")
|
||||
case binding.ERR_ALPHA_DASH_DOT:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.alpha_dash_dot_error")
|
||||
case validation.ErrGitRefName:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.git_ref_name_error")
|
||||
case binding.ERR_SIZE:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.size_error", GetSize(field))
|
||||
case binding.ERR_MIN_SIZE:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.min_size_error", GetMinSize(field))
|
||||
case binding.ERR_MAX_SIZE:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.max_size_error", GetMaxSize(field))
|
||||
case binding.ERR_EMAIL:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.email_error")
|
||||
case binding.ERR_URL:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.url_error", errs[0].Message)
|
||||
case binding.ERR_INCLUDE:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.include_error", GetInclude(field))
|
||||
case validation.ErrGlobPattern:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.glob_pattern_error", errs[0].Message)
|
||||
case validation.ErrRegexPattern:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.regex_pattern_error", errs[0].Message)
|
||||
case validation.ErrUsername:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.username_error")
|
||||
case validation.ErrInvalidGroupTeamMap:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.invalid_group_team_map_error", errs[0].Message)
|
||||
case validation.ErrInvalidBadgeSlug:
|
||||
data["ErrorMsg"] = trName + l.TrString("form.invalid_slug_error")
|
||||
default:
|
||||
msg := errs[0].Classification
|
||||
if msg != "" && errs[0].Message != "" {
|
||||
msg += ": "
|
||||
}
|
||||
|
||||
msg += errs[0].Message
|
||||
if msg == "" {
|
||||
msg = l.TrString("form.unknown_error")
|
||||
}
|
||||
data["ErrorMsg"] = trName + ": " + msg
|
||||
}
|
||||
|
||||
return errs
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/translation"
|
||||
|
||||
"gitea.com/go-chi/binding"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type testRangeForm struct {
|
||||
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, "Hours", errorFieldName)
|
||||
assert.Equal(t, []string{"Hours"}, fieldNames)
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func Bind[T any](_ T) 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)
|
||||
_ = 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)
|
||||
}
|
||||
@@ -37,6 +37,10 @@ func SetForm(dataStore reqctx.ContextDataProvider, obj any) {
|
||||
dataStore.GetData()["__form"] = obj
|
||||
}
|
||||
|
||||
func IsFormSet(dataStore reqctx.RequestDataStore) bool {
|
||||
return dataStore.GetData()["__form"] != nil
|
||||
}
|
||||
|
||||
// GetForm returns the validate form information
|
||||
func GetForm[T any](dataStore reqctx.RequestDataStore) T {
|
||||
form, ok := dataStore.GetData()["__form"].(T)
|
||||
|
||||
Reference in New Issue
Block a user