1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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 _ binding.StructValidator = &DefaultValidator{}
- func (v *DefaultValidator) ValidateStruct(obj interface{}) error {
- if kindOfData(obj) == reflect.Struct {
- v.lazyinit()
- if err := v.validate.Struct(obj); err != nil {
- return err
- }
- }
- return nil
- }
- func (v *DefaultValidator) Engine() interface{} {
- v.lazyinit()
- return v.validate
- }
- func (v *DefaultValidator) lazyinit() {
- v.once.Do(func() {
- v.validate = validator.New()
- v.validate.SetTagName("validate")
- _ = v.validate.RegisterValidation("phone", phone)
- _ = v.validate.RegisterValidation("idcard", idcard)
- _ = v.validate.RegisterValidation("chinesename", chinesename)
- })
- }
- func kindOfData(data interface{}) reflect.Kind {
- value := reflect.ValueOf(data)
- valueType := value.Kind()
- if valueType == reflect.Ptr {
- valueType = value.Elem().Kind()
- }
- return valueType
- }
|