feat: validation returns the original tag for the error field

This commit is contained in:
LinkinStar 2022-11-11 11:24:36 +08:00
parent 3a8742f6fe
commit 0c4eeda383
2 changed files with 36 additions and 4 deletions

View File

@ -3,6 +3,7 @@ package validator
import (
"errors"
"reflect"
"strings"
"github.com/answerdev/answer/internal/base/reason"
"github.com/answerdev/answer/internal/base/translator"
@ -97,9 +98,19 @@ func (m *MyValidator) Check(value interface{}) (errField *ErrorField, err error)
for _, fieldError := range valErrors {
errField = &ErrorField{
Key: translator.GlobalTrans.Tr(m.Lang, fieldError.Field()),
Key: fieldError.Field(),
Value: fieldError.Translate(m.Tran),
}
// get original tag name from value for set err field key.
structNamespace := fieldError.StructNamespace()
_, fieldName, found := strings.Cut(structNamespace, ".")
if found {
originalTag := getObjectTagByFieldName(value, fieldName)
if len(originalTag) > 0 {
errField.Key = originalTag
}
}
return errField, myErrors.BadRequest(reason.RequestFormatError).WithMsg(fieldError.Translate(m.Tran))
}
}
@ -117,3 +128,24 @@ func (m *MyValidator) Check(value interface{}) (errField *ErrorField, err error)
type Checker interface {
Check() (errField *ErrorField, err error)
}
func getObjectTagByFieldName(obj interface{}, fieldName string) (tag string) {
defer func() {
if err := recover(); err != nil {
log.Error(err)
}
}()
objT := reflect.TypeOf(obj)
objT = objT.Elem()
structField, exists := objT.FieldByName(fieldName)
if !exists {
return ""
}
tag = structField.Tag.Get("json")
if len(tag) == 0 {
return structField.Tag.Get("form")
}
return tag
}

View File

@ -77,9 +77,9 @@ type InitBaseInfoReq struct {
SiteName string `validate:"required,gt=0,lte=30" json:"site_name"`
SiteURL string `validate:"required,gt=0,lte=512,url" json:"site_url"`
ContactEmail string `validate:"required,email,gt=0,lte=500" json:"contact_email"`
AdminName string `validate:"required,gt=4,lte=30" json:"admin_name"`
AdminPassword string `validate:"required,gte=8,lte=32" json:"admin_password"`
AdminEmail string `validate:"required,email,gt=0,lte=500" json:"admin_email"`
AdminName string `validate:"required,gt=4,lte=30" json:"name"`
AdminPassword string `validate:"required,gte=8,lte=32" json:"password"`
AdminEmail string `validate:"required,email,gt=0,lte=500" json:"email"`
}
func (r *InitBaseInfoReq) FormatSiteUrl() {