go-playground / validator

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

when the required_if condition does not take effect, it also verifies gt=0 #1136

Open donknap opened 11 months ago

donknap commented 11 months ago

Package version eg. v9, v10:

v10.14.1

Issue, Question or Enhancement:

When using required_if, when the required_if condition does not take effect, it also verifies gt=0

Code sample, to showcase or reproduce:


type ParamsValidate struct {
    Finish      int    `form:"finish" binding:"omitempty,eq=1|eq=0"`
    ChunkNumber int `form:"chunkNumber" binding:"required_if=Finish 0,number,gt=0"`
}

params := ParamsValidate{}
err := ctx.ShouldBindWith(&params, bind.NewCompositeBind(ctx.ContentType(), ctx.Params))

if err != nil {
    fmt.Println(err.Error())
}

when post finish = 0 and chunkNumber = -1:

error message: Key: 'ParamsValidate.ChunkNumber' Error:Field validation for 'ChunkNumber' failed on the 'gt' tag

when post finfish = 1 and chunkNumber = -1 or without chunkNumber :

error message: Key: 'ParamsValidate.ChunkNumber' Error:Field validation for 'ChunkNumber' failed on the 'gt' tag

===================

Question:

ChunkNumber should not be validated when Finish is equal to 1 ?

Because the default value of the int type of the struct is 0,how can I fix it ?

MysteriousPotato commented 11 months ago

ChunkNumber should not be validated when Finish is equal to 1 ?

Because the default value of the int type of the struct is 0,how can I fix it ?

The required_if tag does not stop validation when the requirement is met. For this reason, so long as validation of previous tags succeed, gt=0 will always get evaluated.

It's not clear to me whether ChunkNumber can either be positive or negative when Finish is empty, or if ChunkNumber must be empty when Finish is equal to 1.

Some clarification on your requirements would be helpful as to provide you with a proper solution.

As a side note: