go-playground / validator

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

Validation constraints execute even when field is not required due to required_without #1174

Open aku-ato opened 1 year ago

aku-ato commented 1 year ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

I am using go-playground/validator to validate my struct fields. I've encountered an issue where, if a field (e.g., Password) should be required only under certain conditions using the required_without tag, other validation constraints (like min, max) still get executed even when the field is deemed not required.

I expected other validation constraints not to run if the field is not required due to required_without.

Code sample, to showcase or reproduce:

type User struct {
    Password    *string `validate:"required_without=UpdatedAt,min=9,max=20"`
    UpdatedAt   *time.Time
}

// Example:
// In an update operation, where UpdatedAt is set, the Password field should be optional. 
// But when validating a User instance with UpdatedAt set and an empty or short password, 
// validation errors for min and max constraints still appear. 
// This behavior is unexpected since required_without should make the Password field optional in this context.
fvilpoix commented 7 months ago

I found the solution here https://github.com/go-playground/validator/issues/624#issuecomment-937714455

type User struct {
    Password    *string `validate:"required_without=UpdatedAt,omitempty,min=9,max=20"`
    UpdatedAt   *time.Time
}