go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

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

Open aria3ppp opened 1 year ago

aria3ppp commented 1 year ago

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!

udayraj-rzp commented 1 month ago

+1, faced the same issue when using optional fields from grpc protos. Have to resort using nil check