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

Unexpected behavior validating minimums #165

Open adrianbielsa1 opened 2 years ago

adrianbielsa1 commented 2 years ago

Hi! I stumbled upon the following situation: validating a number's minimum threshold does not work as intended when said threshold is 0.

The following snippet works as expected, printing "must be greater than 1":

data := float64(1)

err := validation.Validate(data,
    validation.Min(float64(1)).Exclusive(),
)

fmt.Println(err)

However, changing the threshold to 0 nullifies the error:

data := float64(0)

err := validation.Validate(data,
    validation.Min(float64(0)).Exclusive(),
)

fmt.Println(err)

^ prints "\" (i.e. no error).

call-stack commented 2 years ago

When you initialize data as 0 it treat is as an empty value when doing the validation. Hence you are getting nil. Screenshot 2022-01-31 at 10 04 06 PM

adrianbielsa1 commented 2 years ago

Then, how would you validate that a value must be greater than 0?

call-stack commented 2 years ago

You can do something like this. Since it is treating 0 as empty.

data := float64(0)
err := validation.Validate(data,
    validation.Min(float64(0)).Exclusive(),
    validation.NilOrNotEmpty.Error("must be greater than 0"),
)
fmt.Println(err)