Failed string field detection - govalidator

I am experimenting with govalidator - https://github.com/asaskevich/govalidator

I would like to know if it is possible to determine which field in the structure failed the validation check so that I can return an appropriate error message. 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
}

      

+3


source to share


1 answer


This looks like issue / 67 :

At this point, it gives an error like this:

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

      



I am creating a function ErroByField(e error, field string)

that will return an error for the specified structure field or empty string otherwise, I hope this is 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
}

      

+3


source







All Articles