我使用github.com/go-playground/validator/v10.
我创建了一个自定义验证器(stringMinLength
),用于验证字符串是否长于给定长度。如果要验证的字符串长度小于给定的最小允许长度,那么我想设置一条描述问题的错误消息。
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
"strconv"
"unicode/utf8"
)
type Profile struct {
Name string `validate:"required,stringMinLength=3"`
Age uint `validate:"required,gt=10"`
}
// See https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions
func stringMinLength(inField validator.FieldLevel) bool {
//var value string = inField.Field().String()
value, kind, nullable := inField.ExtractType(inField.Field())
param := inField.Param()
fmt.Printf("=> name: [%s]n", inField.FieldName())
fmt.Printf("=> tag: [%s]n", inField.GetTag())
fmt.Printf("=> struct field name: [%s]n", inField.StructFieldName())
fmt.Printf("=> param: [%s]n", param)
fmt.Printf("=> value: [%s]n", value.String())
fmt.Printf("=> kind: [%s]n", kind.String())
if nullable {
fmt.Printf("=> nullable: truen")
} else {
fmt.Printf("=> nullable: falsen")
}
// The parameter must be an integer!
minLength, err := strconv.ParseUint(param, 10, 32)
if err != nil {
panic(fmt.Sprintf(`stringMinLength parameter must be an unsigned integer! (got "%s" instead)`, param))
}
status := uint64(utf8.RuneCountInString(value.String())) >= minLength
if !status {
// I want to register an error message that informs the caller that the given name is too short
}
return status
}
func main() {
myValidator := validator.New()
if err := myValidator.RegisterValidation("stringMinLength", stringMinLength); err != nil {
panic(err)
}
// ===================================================
// Test SUCCESS
// ===================================================
profile := Profile{
Name: "Joe",
Age: 25,
}
if err := myValidator.Struct(profile); err != nil {
panic(err)
}
fmt.Printf("SUCCESS (as expected) => OKn")
// ===================================================
// Test FAILURE
// ===================================================
profile = Profile{
Name: "IT",
Age: 9,
}
if err := myValidator.Struct(profile); err != nil {
fmt.Printf("FAILURE (as expected) => OKn")
fmt.Printf("err: %Tn", err) // => validator.ValidationErrors
errors := err.(validator.ValidationErrors)
for _, v := range errors {
fmt.Printf("%sn", v.Error())
}
}
}
你可以在这里测试:https://go.dev/play/p/Ol6sq8hAyjq
:如何从我的自定义验证器(stringMinLength
)返回错误消息?
我读过关于"翻译"的信息,但我不明白翻译怎么能解决这个问题。
看来我现在需要做的事情是不可能的:
https://github.com/go-playground/validator/issues/669
该功能将被添加到版本11:
https://github.com/go-playground/validator/issues?q=is%3Aissue + % 3 aopen +标签% 3 av11