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.78k stars 224 forks source link

validation.Required treat type *bool as blank value when it set to false #146

Closed siampudan closed 3 years ago

siampudan commented 3 years ago

I've a struct like this :

type SubCategoryReq struct {
    ProductID          int     `json:"product_id"`
    MerchantID         int     `json:"merchant_id"`
    CategoryID         int     `json:"category_id"`
    ProductName        string  `json:"product_name"`
    ProductDescription string  `json:"product_description"`
    ProductPrice       float64 `json:"product_price"`
    IsAvailable        *bool   `json:"is_available"`
    File               string  `json:"file"`
    FileType           string  `json:"file_type"`
}

and validation struct like this :

func (sc SubCategoryReq) SubCategoryReqValidate() error {
    return validation.ValidateStruct(&sc,
        validation.Field(&sc.CategoryID, validation.Required),
        validation.Field(&sc.ProductName, validation.Required),
        validation.Field(&sc.ProductPrice, validation.Required),
        validation.Field(&sc.ProductDescription, validation.Required),
        validation.Field(&sc.IsAvailable, validation.Required),
    )
}

When i create a request from Postman and set json body payload "is_available" : true the validation.Required treat the IsAvailable field as it is. But, when i set "is_available":false the validation.Required treat the IsAvailable field as blank value { "is_available": "cannot be blank" }. It looks like the validation.Required failed to detect the *bool type when it set to 'false'. To parse the request json payload to the model struct, i use Gin Framework (ShouldBindJSON). Thanks.

qiangxue commented 3 years ago

This is by design, see: https://github.com/go-ozzo/ozzo-validation/blob/master/required.go#L14-L20 You should use NotNil in your case: https://github.com/go-ozzo/ozzo-validation/blob/master/not_nil.go#L13

siampudan commented 3 years ago

hmm, i see. thanks..