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
}
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
}