56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
|
package validator
|
||
|
|
||
|
import (
|
||
|
"reflect"
|
||
|
"sync"
|
||
|
|
||
|
"github.com/gin-gonic/gin/binding"
|
||
|
"github.com/go-playground/validator/v10"
|
||
|
)
|
||
|
|
||
|
type DefaultValidator struct {
|
||
|
once sync.Once
|
||
|
validate *validator.Validate
|
||
|
}
|
||
|
|
||
|
var Validator binding.StructValidator = &DefaultValidator{}
|
||
|
|
||
|
func (v *DefaultValidator) ValidateStruct(obj any) error {
|
||
|
if kindOfData(obj) == reflect.Struct {
|
||
|
|
||
|
v.lazyinit()
|
||
|
|
||
|
if err := v.validate.Struct(obj); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (v *DefaultValidator) Engine() any {
|
||
|
v.lazyinit()
|
||
|
return v.validate
|
||
|
}
|
||
|
|
||
|
func (v *DefaultValidator) lazyinit() {
|
||
|
v.once.Do(func() {
|
||
|
v.validate = validator.New()
|
||
|
v.validate.SetTagName("validate")
|
||
|
_ = v.validate.RegisterValidation("chinesePhone", chinesePhone)
|
||
|
_ = v.validate.RegisterValidation("isoPhone", isoPhone)
|
||
|
_ = v.validate.RegisterValidation("idCard", idCard)
|
||
|
_ = v.validate.RegisterValidation("chineseName", chineseName)
|
||
|
_ = v.validate.RegisterValidation("year", year)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func kindOfData(data any) reflect.Kind {
|
||
|
value := reflect.ValueOf(data)
|
||
|
valueType := value.Kind()
|
||
|
|
||
|
if valueType == reflect.Ptr {
|
||
|
valueType = value.Elem().Kind()
|
||
|
}
|
||
|
return valueType
|
||
|
}
|