fix(validation): correct CustomValidator and strutils.Parser handling, add tests

This commit is contained in:
yusing
2025-10-15 14:20:47 +08:00
parent b09bfd6c1e
commit feafdf05f2
9 changed files with 519 additions and 41 deletions

View File

@@ -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
}