Skip to content
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

Required validator ignores 0 assuming the field is not provided #734

Closed
hamidr opened this issue Feb 26, 2021 · 4 comments
Closed

Required validator ignores 0 assuming the field is not provided #734

hamidr opened this issue Feb 26, 2021 · 4 comments

Comments

@hamidr
Copy link

hamidr commented Feb 26, 2021

Package version: v10

Issue:

Hey, folks :)
Required validator ignores 0 assuming the field is not provided.
This seems to be a default value issue.
I guess it can't be fixed?

Code sample, to showcase or reproduce:

import  "github.com/go-playground/validator/v10"

type Filter struct {
	Skip    int           `json:"skip,integer" form:"skip" validate:"required"`
}

f := Filter { Skip: 0 }
if err := validator.New().Struct(query); err != nil {
    print("No 0 is not an integer")
} else { //it should be.
    print("https://en.wikipedia.org/wiki/Integer")
}
@hamidr
Copy link
Author

hamidr commented Feb 26, 2021

Haha... This actually is a "required" problem because it seems that 0 means the value is not provided.

@hamidr hamidr changed the title Zero(0) is an integer. Required validator ignores 0 assuming the field is not provided Feb 26, 2021
@atsikham
Copy link

atsikham commented Mar 4, 2021

The same for empty string. Are there any examples with the case when string is required but might be empty?

@MiraiTunga
Copy link

you can use gt as a work around e.g

type Filter struct {
	Skip    int    `json:"skip,integer" form:"skip" validate:"gt=-1"`
}

@deankarn
Copy link

Hello @hamidr

sorry I’ve let this issue linger been rather busy lately.

so this has been asked and covered many times in separate issue but to reiterate.

If you read the “required” documentation carefully you will note it states it validates that the value isn’t it’s types default. So “required” is working as intended.

Go does not have a notion of uninitialized variables and so the default is always the types default.

Go also does not have a nice way to denote an optional variable like rusts “Option” either but there are 2 options in Go:

  1. Make the field a pointer and then the default value will be nil and if the value is present it won’t be nil anymore.
  2. Create a custom type similar to the sql.NullString, sql.Null* custom types and then register a custom type function with the validator library.

I hope this clarifies things :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants