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

Behaviour with nil pointers seems a bit inconsistent #1197

Open
2 tasks done
Philio opened this issue Nov 18, 2023 · 0 comments
Open
2 tasks done

Behaviour with nil pointers seems a bit inconsistent #1197

Philio opened this issue Nov 18, 2023 · 0 comments

Comments

@Philio
Copy link

Philio commented Nov 18, 2023

  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

10.16.0

Issue, Question or Enhancement:

I recently changed a few of the DTOs in my project to use pointers to support PATCH requests.
For the most part this was uneventful and the recent addition of omitnil came in handy, however trying to make required fields optional for PATCH requests threw up some inconsistent behaviour.

I added a custom validator is_patch to check if the request was a PATCH and the assumption that replacing all required validations with required|is_patch would give the desired behavior.

Validator implementation:

func IsPatch(ctx context.Context, _ validator.FieldLevel) bool {
	method, ok := ctx.Value(ValidatorRequestMethod).(string)
	if !ok {
		return false
	}
	if strings.ToLower(method) == "patch" {
		return true
	}
	return false
}

My custom validator is registered with check null as true:

validate.RegisterValidationCtx("is_patch", IsPatch, true)

But this didn't work, I debugged and saw my validator wasn't even getting called.

It's due to the required validator not checking nils (even though the implementation seems to support nil pointer checks). The first validator within an or seems to determine whether validation will check nils or not.

Hence, is_patch|required works fine.

I would assume that the order of validators when using or would be irrelevant, I couldn't find anything in the docs about this.
In addition the error logged says that validation failed on is_patch, which was not strictly correct.

Although I have a working solution, thought it was worth logging this, or perhaps there is an alternative/better approach that I've missed?

Code sample, to showcase or reproduce:

N/A

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