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

Access gin request Context from custom validators #2741

Open
samber opened this issue May 30, 2021 · 3 comments · May be fixed by #2877
Open

Access gin request Context from custom validators #2741

samber opened this issue May 30, 2021 · 3 comments · May be fixed by #2877

Comments

@samber
Copy link

samber commented May 30, 2021

The StructValidator interface does not allow passing *gin.Context.

For example, I would like to access c.Params from my validator.

Current interface signature:

type StructValidator interface {
	ValidateStruct(interface{}) error
	Engine() interface{}
}

It would be very nice to add an interface such as:

type StructValidatorWithContext interface {
	ValidateStructWithContext(interface{}) error
	Engine() interface{}
}
@kszafran
Copy link
Contributor

kszafran commented Aug 5, 2021

Related to this: #1489

I agree that this could be helpful. The validator library supports contextual validation if you call (*Validate).StructCtx(...) instead of (*Validate).Struct(...). I imagine that could be implemented by passing *gin.Context as the ctx argument since it implements context.Context.

For example, in my case, I'd like to make a field required or not, based on a query param. If gin context was passed on to the validator, I could do that.

I imagine the StructValidator validator could be extended with one more method:

ValidateStructCtx(context.Context, interface{}) error

Or if this cannot be done, because it's a breaking change, then an "extension" interface could be defined, similar to what @samber proposed:

type StructValidatorWithContext interface {
	StructValidator
	ValidateStructCtx(context.Context, interface{}) error
}

And then, when binding, the code could check if the validator implementation is an instance of StructValidatorWithContext. Kind of like the standard library sometimes checks if your io.Reader is also an io.ReadCloser.

@kszafran
Copy link
Contributor

@samber Check out my PR. I implemented passing context to validators: #2877

@kaysonwu
Copy link

I have also encountered this issue, which can help enhance the form validation function. I look forward to going online soon.

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

Successfully merging a pull request may close this issue.

3 participants