-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
FieldError Field function returns struct name instead of JSON tag #337
Comments
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 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:
Thanks for your answer! :) |
I also understood that "the tag name taking precedence over the fields actual name" meant that |
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? |
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" |
For folks looking to implement this with gin gonic router here's how you can register the
|
Hi, apparently the doc is still not updated. Any news on this? |
I've registered tag name parser: validate = validator.New()
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
return name
}) I attempt to validate following struct: type Credentials struct {
Password string `json:"password" validate:"required"`
PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"`
} However, I'm getting this error: What I expected to see: Am I missing something? |
@ameghdadian Could you ask this question in the |
I do have this struct:
Then i'm using
validate.Struct(data)
and i'm ranging overValidationErrors
.Every
Field()
onerror
inValidationErrors
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.
The text was updated successfully, but these errors were encountered: