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

An explanation of how required works. #203

Open
SharkFourSix opened this issue Apr 6, 2023 · 2 comments
Open

An explanation of how required works. #203

SharkFourSix opened this issue Apr 6, 2023 · 2 comments
Assignees

Comments

@SharkFourSix
Copy link
Contributor

System (please complete the following information):

  • OS: linux
  • GO Version: 1.20
  • Pkg Version: 1.4.6

Describe the bug

Not necessarily a bug.

How exactly does required work?

Suppose we have the following case

type Foo {
    Name int `validate:"required|int|between:1,999" label: "name"`
}

foo := &Foo{Name: 4}

v := validate.Struct(&foo)

v.Validate()

I'm getting a validation error name is required to not be empty as if I did not specify the the field Name. If I leave out the required validator it works.

So the question is, when exactly to we need to use the required validator?

Because if I don't specify required are we saying that the field is optional? Or does required only work with pointer types?

Can you please explain the use cases and effects of this. I have just discovered that my validation rules were not running before because I made this PR #202 and that is why I'm confused now.

To Reproduce

Expected behavior

I expect validation to pass when required is specified and when a field has a valid value.

Screenshots

n/a

Additional context

n/a

@inhere
Copy link
Member

inhere commented Apr 7, 2023

If not required, it will only be validated if the value is not empty(nil,zero-value).

So without specifying required, it can be said that the field is optional.

@SharkFourSix
Copy link
Contributor Author

If not required, it will only be validated if the value is not empty(nil,zero-value).

So without specifying required, it can be said that the field is optional.

Alright, but now I'm seeing that when I remove required from a string field, my custom filter and validator function does not get called and I'm ending up passing invalid data which gets accepted, which should not happen 😔

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