检测失败的结构字段 – govalidator

huangapple go评论131阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2015年8月10日 00:18:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/31906246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定