作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在试验 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
}
最佳答案
这似乎类似于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
}
关于go - 检测失败的结构字段 - govalidator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906246/
我正在试验 govalidator - https://github.com/asaskevich/govalidator 我想知道是否可以检测结构中的哪个字段未通过验证检查,以便我可以返回适当的错误
我是一名优秀的程序员,十分优秀!