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

Require integer to exist and let it equal 0 #87

Open
veeral-patel opened this issue Dec 17, 2019 · 4 comments
Open

Require integer to exist and let it equal 0 #87

veeral-patel opened this issue Dec 17, 2019 · 4 comments

Comments

@veeral-patel
Copy link

Hi, thanks for this great library! So I know that the 'required' struct tag raises an error if you provide an integer that equals 0.

I know why this is the case -- the zero value for integers is, well, 0, so it's impossible to tell whether a value is 0 because it's missing or because it's provided and its actually 0. To error on the side of caution, govalidator decided to not allow 0 values for integers.

If I wanted to write a custom rule, however, that required a struct to have a certain integer field, which is allowed to be 0, how would I go about doing that? Any advice?

@veeral-patel
Copy link
Author

@thedevsaddam I found a similar issue: #9

Where you linked to this page: https://github.com/thedevsaddam/govalidator/blob/master/doc/SIMPLE_STRUCT_VALIDATION.md

However, I didn't see anything on this page that would solve my problem! Perhaps it is out of date?

Thanks again!

@thedevsaddam
Copy link
Owner

Probably you can use min:numeric rule

@veeral-patel
Copy link
Author

veeral-patel commented Dec 18, 2019

@thedevsaddam Thanks for your reply! Sorry for closing/reopening this ticket on accident.

Here are my validation rules:

	validator := govalidator.New(govalidator.Options{
		Data: &requestBody,
		Rules: govalidator.MapData{
			"title":      []string{"required", "max:255"},
			"x":          []string{"required", "min:0", "max:11"},
			"y":          []string{"required", "min:0"},
			"w":          []string{"required", "min:1", "max:12"},
			"h":          []string{"required", "min:1"},
			"panel_type": []string{"required", "max:255"},
		},
	})

And here's the errors I get from govalidator:

Screen Shot 2019-12-18 at 10 16 13 AM

Note that I provided a value for x and y (0) but govalidator tells me x and y are required.

If I set x to any integer >= 1, then I don't get this "field is required" error in the two fields. I think what's happening is that required requires integers to not be 0 (as per the README).

In my example, how can I require the x field but also allow it to be 0?

@thedevsaddam
Copy link
Owner

Can you please share the data struct that you are using

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

2 participants