mirror of
https://github.com/yusing/godoxy.git
synced 2026-03-30 13:51:52 +02:00
fix(validation): correct CustomValidator and strutils.Parser handling, add tests
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package serialization
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
gperr "github.com/yusing/goutils/errs"
|
||||
)
|
||||
@@ -9,10 +11,6 @@ var validate = validator.New()
|
||||
|
||||
var ErrValidationError = gperr.New("validation error")
|
||||
|
||||
type CustomValidator interface {
|
||||
Validate() gperr.Error
|
||||
}
|
||||
|
||||
func Validator() *validator.Validate {
|
||||
return validate
|
||||
}
|
||||
@@ -23,3 +21,40 @@ func MustRegisterValidation(tag string, fn validator.Func) {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
type CustomValidator interface {
|
||||
Validate() gperr.Error
|
||||
}
|
||||
|
||||
var validatorType = reflect.TypeFor[CustomValidator]()
|
||||
|
||||
func ValidateWithCustomValidator(v reflect.Value) gperr.Error {
|
||||
if v.Kind() == reflect.Pointer {
|
||||
if v.IsNil() {
|
||||
// return nil
|
||||
return validateWithValidator(reflect.New(v.Type().Elem()))
|
||||
}
|
||||
if v.Type().Implements(validatorType) {
|
||||
return v.Interface().(CustomValidator).Validate()
|
||||
}
|
||||
return validateWithValidator(v.Elem())
|
||||
} else {
|
||||
vt := v.Type()
|
||||
if vt.PkgPath() != "" { // not a builtin type
|
||||
if vt.Implements(validatorType) {
|
||||
return v.Interface().(CustomValidator).Validate()
|
||||
}
|
||||
if v.CanAddr() {
|
||||
return validateWithValidator(v.Addr())
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateWithValidator(v reflect.Value) gperr.Error {
|
||||
if v.Type().Implements(validatorType) {
|
||||
return v.Interface().(CustomValidator).Validate()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user