go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.07k stars 1.29k forks source link

Behaviour with nil pointers seems a bit inconsistent #1197

Open Philio opened 7 months ago

Philio commented 7 months ago

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