英文:
Detecting failed struct field - govalidator
问题
我正在尝试使用govalidator - https://github.com/asaskevich/govalidator。
我想知道是否可以检测到结构体中哪个字段未通过验证,以便我可以返回适当的错误消息。例如:
type Post struct {
Title string `valid:"alphanum,required"`
Message string `valid:"required"`
}
result, err := govalidator.ValidateStruct(post)
if err != nil {
//如果标题缺失,则显示错误1
//如果消息缺失,则显示错误2
}
英文:
I'm experimenting with govalidator - https://github.com/asaskevich/govalidator
I would like to know whether it's possible to detect which field in a struct has failed a validation check so that I can return an appropriate error message. So for example:
type Post struct {
Title string `valid:"alphanum,required"`
Message string `valid:"required"`
}
result, err := govalidator.ValidateStruct(post)
if err != nil {
//if title is missing then show error 1
//if message is missing then show error 2
}
答案1
得分: 3
这似乎与问题/67相似:
> 目前它会给出以下错误:
标题:My123不符合alpha规则;
作者IP:123不符合ipv4规则;
> 我创建了一个ErroByField(e error, field string)
函数,它将返回指定结构体字段的错误,否则返回空字符串,希望这对你有帮助。
> 例如:
type Post struct {
Title string `valid:"alpha,required"`
Message string `valid:"ascii"`
AuthorIP string `valid:"ipv4"`
}
post := &Post{"My123", "duck13126", "123"}
result, err := govalidator.ValidateStruct(post)
titleError := govalidator.ErrorByField(err, "Title")
if titleError != "" {
println(titleError) // -> My123不符合alpha规则
}
英文:
This seems to be similar to issue/67:
> At this moment it gives error like this:
Title: My123 does not validate as alpha;
AuthorIP: 123 does not validate as ipv4;
> I create function ErroByField(e error, field string)
that will return error for specified field of struct or empty string otherwise, I hope that it will be helpful.
> For example:
type Post struct {
Title string `valid:"alpha,required"`
Message string `valid:"ascii"`
AuthorIP string `valid:"ipv4"`
}
post := &Post{"My123", "duck13126", "123"}
result, err := govalidator.ValidateStruct(post)
titleError := govalidator.ErrorByField(err, "Title")
if titleError != "" {
println(titleError) // -> My123 does not validate as alpha
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论