检测失败的struct字段 - govalidator

时间:2015-08-09 16:18:25

标签: go

我正在尝试使用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 {
    //if title is missing then show error 1
    //if message is missing then show error 2
}

1 个答案:

答案 0 :(得分:3)

这似乎与issue/67类似:

  

此时它会出现如下错误:

Title: My123 does not validate as alpha;
AuthorIP: 123 does not validate as ipv4;
  

我创建了函数ErroByField(e error, field string),它将返回struct的指定字段或空字符串的错误,否则,我希望它会有所帮助。

     

例如:

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
}