asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.05k stars 555 forks source link

BUG (?) validating required fields in a list of structs #267

Open ahavriluk opened 6 years ago

ahavriluk commented 6 years ago

Validator fails to validate elements (structs) of a list when they have required fields.

I have the following structs:

type CustomerOption struct { Name string valid:"required" json:"name" Value string json:"value" }

// CustomerOptions a set of customer options (name, value pairs) // swagger:model CustomerOptions type CustomerOptions struct { CustomerOptions []CustomerOption valid:"required" json:"List" }

func (custOpt *CustomerOption) Validate() error { validation.AddCustomValidators()

if _, err := govalidator.ValidateStruct(custOpt); err != nil {
    return oshandlers.NewValidationError().Add(err)
}
return nil

}

func (custOpts *CustomerOptions) Validate() error { validation.AddCustomValidators()

if _, err := govalidator.ValidateStruct(custOpts); err != nil {
    return oshandlers.NewValidationError().Add(err)
}
return nil

}

Context("CustomerOptions.Validate()", func() { //The following test passes: It("should error if no options", func() { custOpts := types.CustomerOptions{ CustomerOptions: nil, } err := custOpts.Validate() Expect(err).To(MatchError(oshandlers.NewValidationError().Field("List", "required"))) })

//But this one fails complaining that 'List' is required which is wrong since the List (CustomerOptions is provided). It should have failed validating CustomerOption. It used to work correctly before (I had older version).

    It("should error if no name", func() {
        custOpts := types.CustomerOptions{
            CustomerOptions: []types.CustomerOption{
                types.CustomerOption{
                    Name:  "",
                },
            },
        }
        err := custOpts.Validate()
        Expect(err).To(MatchError(oshandlers.NewValidationError().Field("name", "required")))
    })

})

sergeyglazyrindev commented 3 years ago

Hello guys! I forked this package cause owner disappeared. Hope, he will be back, but it would be easier to merge these changes back if he is back Link to my repo: create issue there and we'll discuss it.