fix(binding): dereference pointer to struct (#3199)
This commit is contained in:
parent
86ff4a64c7
commit
82bcd6d39b
@ -54,7 +54,10 @@ func (v *defaultValidator) ValidateStruct(obj any) error {
|
|||||||
value := reflect.ValueOf(obj)
|
value := reflect.ValueOf(obj)
|
||||||
switch value.Kind() {
|
switch value.Kind() {
|
||||||
case reflect.Ptr:
|
case reflect.Ptr:
|
||||||
|
if value.Elem().Kind() != reflect.Struct {
|
||||||
return v.ValidateStruct(value.Elem().Interface())
|
return v.ValidateStruct(value.Elem().Interface())
|
||||||
|
}
|
||||||
|
return v.validateStruct(obj)
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
return v.validateStruct(obj)
|
return v.validateStruct(obj)
|
||||||
case reflect.Slice, reflect.Array:
|
case reflect.Slice, reflect.Array:
|
||||||
|
@ -192,6 +192,30 @@ func TestValidatePrimitives(t *testing.T) {
|
|||||||
assert.Equal(t, "value", str)
|
assert.Equal(t, "value", str)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type structModifyValidation struct {
|
||||||
|
Integer int
|
||||||
|
}
|
||||||
|
|
||||||
|
func toZero(sl validator.StructLevel) {
|
||||||
|
var s *structModifyValidation = sl.Top().Interface().(*structModifyValidation)
|
||||||
|
s.Integer = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateAndModifyStruct(t *testing.T) {
|
||||||
|
// This validates that pointers to structs are passed to the validator
|
||||||
|
// giving us the ability to modify the struct being validated.
|
||||||
|
engine, ok := Validator.Engine().(*validator.Validate)
|
||||||
|
assert.True(t, ok)
|
||||||
|
|
||||||
|
engine.RegisterStructValidation(toZero, structModifyValidation{})
|
||||||
|
|
||||||
|
s := structModifyValidation{Integer: 1}
|
||||||
|
errs := validate(&s)
|
||||||
|
|
||||||
|
assert.Nil(t, errs)
|
||||||
|
assert.Equal(t, s, structModifyValidation{Integer: 0})
|
||||||
|
}
|
||||||
|
|
||||||
// structCustomValidation is a helper struct we use to check that
|
// structCustomValidation is a helper struct we use to check that
|
||||||
// custom validation can be registered on it.
|
// custom validation can be registered on it.
|
||||||
// The `notone` binding directive is for custom validation and registered later.
|
// The `notone` binding directive is for custom validation and registered later.
|
||||||
|
Loading…
Reference in New Issue
Block a user