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

[discussion] How to validate an optional field? #177

Open
aria3ppp opened this issue Dec 10, 2022 · 0 comments
Open

[discussion] How to validate an optional field? #177

aria3ppp opened this issue Dec 10, 2022 · 0 comments

Comments

@aria3ppp
Copy link

aria3ppp commented Dec 10, 2022

Consider this struct:

type Foo struct {
    Bar *int `json:"bar"`
}

func (r Foo) Validate() error {
    return validation.ValidateStruct(
         &r,
         validation.Field(
              &r.Bar,
              validation.When(
                   r.Bar != nil,
                   validation.Required,
                   validation.Min(2),
              ),  
         ),
    )
}

How to say if Bar provided then validate it is bigger than e.g. 2 else do not validate as it is optional?
Is my solution the best effort?
I mean if i'm not using validation.When(r.Bar != nil, validation.Required, ...) then it accept 0 value for Bar but that is not my intention!

@aria3ppp aria3ppp reopened this Dec 10, 2022
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

1 participant