I do have this struct:
data := struct {
Email string `validate:"required,email" "json:"email"`
Password string `validate:"required,min=8" "json:"password"`
}{}
Then i'm using validate.Struct(data) and i'm ranging over ValidationErrors.
Every Field() on error in ValidationErrors returns struct field instead of JSON tag.
For example, data.Email has json tag "email", but it retuns "Email" instead.
Why is that? Documentation clearly says it should return JSON tag.
Hey @kerak19 can you point out exactly where in the documentation that it states it returns the json name by default? and I'll correct right away.
as for grabbing the json tag name, you have to register a tag name parser first eg.
validate := New()
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
it's done this way in order to allow for parsing of any tag name like json, bson, sql tags etc...
Please let me know if this was helpful :)
So i probably misunderstood this and thought it's default to take first existing tag name:
// returns the fields name with the tag name taking precedence over the
// fields actual name.
//
// eq. JSON name "fname"
// see ActualField for comparison
Field() string
Thanks for your answer! :)
I also understood that "the tag name taking precedence over the fields actual name" meant that err.Field() would give me the JSON tag name by default.
The documentation definitely makes it look like it will pick something like the JSON tag name. I think it would be very useful to add a sentence to the documentation saying something like "You must implement RegisterTagNameFunc if you want to use a tag rather than the struct field name."
Thanks @pnicolcev-tulipretail I agree, any chance you could make a PR?
Hey @kerak19 can you point out exactly where in the documentation that it states it returns the json name by default? and I'll correct right away.
as for grabbing the
jsontag name, you have to register a tag name parser first eg.validate := New() validate.RegisterTagNameFunc(func(fld reflect.StructField) string { name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] if name == "-" { return "" } return name })it's done this way in order to allow for parsing of any tag name like json, bson, sql tags etc...
Please let me know if this was helpful :)
type RegisterAccountForm struct {
Account int `json:"account" validate:"required"`
Password string `json:"password" validate:"required"`
ConfirmPassword string `json:"confirm_password" validate:"required,eqfield=Password"`
}
but tag "eqfield" seems doesn't work,It returns "password蹇呴』绛変簬ConfirmPassword"
Most helpful comment
I also understood that "the tag name taking precedence over the fields actual name" meant that
err.Field()would give me the JSON tag name by default.