File tree Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Original file line number Diff line number Diff line change @@ -54,7 +54,10 @@ func (v *defaultValidator) ValidateStruct(obj any) error {
5454 value := reflect .ValueOf (obj )
5555 switch value .Kind () {
5656 case reflect .Ptr :
57- return v .ValidateStruct (value .Elem ().Interface ())
57+ if value .Elem ().Kind () != reflect .Struct {
58+ return v .ValidateStruct (value .Elem ().Interface ())
59+ }
60+ return v .validateStruct (obj )
5861 case reflect .Struct :
5962 return v .validateStruct (obj )
6063 case reflect .Slice , reflect .Array :
Original file line number Diff line number Diff line change @@ -192,6 +192,30 @@ func TestValidatePrimitives(t *testing.T) {
192192 assert .Equal (t , "value" , str )
193193}
194194
195+ type structModifyValidation struct {
196+ Integer int
197+ }
198+
199+ func toZero (sl validator.StructLevel ) {
200+ var s * structModifyValidation = sl .Top ().Interface ().(* structModifyValidation )
201+ s .Integer = 0
202+ }
203+
204+ func TestValidateAndModifyStruct (t * testing.T ) {
205+ // This validates that pointers to structs are passed to the validator
206+ // giving us the ability to modify the struct being validated.
207+ engine , ok := Validator .Engine ().(* validator.Validate )
208+ assert .True (t , ok )
209+
210+ engine .RegisterStructValidation (toZero , structModifyValidation {})
211+
212+ s := structModifyValidation {Integer : 1 }
213+ errs := validate (& s )
214+
215+ assert .Nil (t , errs )
216+ assert .Equal (t , s , structModifyValidation {Integer : 0 })
217+ }
218+
195219// structCustomValidation is a helper struct we use to check that
196220// custom validation can be registered on it.
197221// The `notone` binding directive is for custom validation and registered later.
You can’t perform that action at this time.
0 commit comments