Skip to content

Commit 82bcd6d

Browse files
authored
fix(binding): dereference pointer to struct (#3199)
1 parent 86ff4a6 commit 82bcd6d

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

binding/default_validator.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff 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:

binding/validate_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff 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.

0 commit comments

Comments
 (0)