asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.04k stars 555 forks source link

Incorrect field name is selected when validating slices #351

Open leighmcculloch opened 5 years ago

leighmcculloch commented 5 years ago

Bug

When a type nested inside a slice is being validated the field name that gets attached to the error is sometimes incorrect. When the parent field is given a json name, the parent field gets used, but when the parent field doesn't have a json name, the child field gets used. In both cases I think the child field should be used for consistency with all other cases.

Examples

type Details struct {
    Email string `json:"email" valid:"email"`
}

type Address struct {
    CountryCode string `json:"country_code" valid:"ISO3166Alpha3"`
}

type Person struct {
    Details   Details   `json:"details"`
    Addresses []Address `json:"addresses"`
}

Example

When the parent Addresses has a json tag name addresses, the validation error on the CountryCode field gets given the name addresses:

Details.email: gogopher@example-com does not validate as email
Addresses.1.addresses: GBP does not validate as ISO3166Alpha3

https://play.golang.org/p/eH93fHIiCCR

Example 2

When the parent Addresses doesn't have a json tag name, the validation error on the CountryCode field gets given the name country_code:

Details.email: gogopher@example-com does not validate as email
Addresses.1.country_code: GBP does not validate as ISO3166Alpha3

https://play.golang.org/p/8GZK-XRqCjp

sergeyglazyrindev commented 3 years ago

Hello guys! I forked this package cause owner disappeared. Hope, he will be back, but it would be easier to merge these changes back if he is back Link to my repo: create issue there and we'll discuss it.