英文:
Golang validator package with error rename field
问题
我尝试使用golang的验证器包<https://pkg.go.dev/github.com/go-playground/validator/v10>。有没有办法在返回的错误中掩盖字段?例如,假设我有一个类似以下结构的结构体,用于执行结构体验证:
type SignInUserData struct {
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
}
如果我的错误映射如下:
validationErrors := err.(validator.ValidationErrors)
for _, fieldError := range validationErrors {
fmt.Println(fieldError.Field())
}
我得到的字段名是"Email"或"Password"。我希望返回的是字段的其他名称,例如"Email"变成"Email Address",或者"Password"变成"Secret"。
有办法做到吗?谢谢。
英文:
I tried to use golang validator package
<https://pkg.go.dev/github.com/go-playground/validator/v10>
is there a way to mask the field for the returned error? example below, let's say I have a struct like the following, to perform struct validation
type SignInUserData struct {
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
}
if my error is mapping like this:
validationErrors := err.(validator.ValidationErrors)
for _, fieldError := range validationErrors {
fmt.println(fieldError.Field())
}
I get the field name, like "Email" or "Password". I want what is returned is the other name of the field, for example "Email" becomes "Email Address", or "Password" becomes "Secret".
Is there a way to do it? Thank You ..
答案1
得分: 1
你可以使用(*Validate).RegisterTagNameFunc来注册一个函数,以获取StructFields的替代名称。
例如,注册一个函数来从name
标签中获取替代名称:
package main
import (
"fmt"
"reflect"
"github.com/go-playground/validator/v10"
)
type SignInUserData struct {
Email string `json:"email" validate:"required" name:"Email Address"`
Password string `json:"password" validate:"required" name:"Secret"`
}
func main() {
validate := validator.New()
validate.RegisterTagNameFunc(func(field reflect.StructField) string {
return field.Tag.Get("name")
})
data := &SignInUserData{}
err := validate.Struct(data)
if err != nil {
validationErrors, ok := err.(validator.ValidationErrors)
if ok {
for _, fieldError := range validationErrors {
fmt.Println(fieldError.Field())
}
}
}
}
英文:
You can use (*Validate).RegisterTagNameFunc to register a function to get alternate names for StructFields.
For example, register a function to get the alternative name from the name
tag:
package main
import (
"fmt"
"reflect"
"github.com/go-playground/validator/v10"
)
type SignInUserData struct {
Email string `json:"email" validate:"required" name:"Email Address"`
Password string `json:"password" validate:"required" name:"Secret"`
}
func main() {
validate := validator.New()
validate.RegisterTagNameFunc(func(field reflect.StructField) string {
return field.Tag.Get("name")
})
data := &SignInUserData{}
err := validate.Struct(data)
if err != nil {
validationErrors, ok := err.(validator.ValidationErrors)
if ok {
for _, fieldError := range validationErrors {
fmt.Println(fieldError.Field())
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论