Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting failed struct field - govalidator

Tags:

go

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
}
like image 974
tommyd456 Avatar asked Aug 03 '26 00:08

tommyd456


1 Answers

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
}
like image 134
VonC Avatar answered Aug 05 '26 16:08

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!