validator.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package validator
  2. import (
  3. "reflect"
  4. "sync"
  5. "github.com/gin-gonic/gin/binding"
  6. "github.com/go-playground/validator/v10"
  7. )
  8. type DefaultValidator struct {
  9. once sync.Once
  10. validate *validator.Validate
  11. }
  12. var _ binding.StructValidator = &DefaultValidator{}
  13. func (v *DefaultValidator) ValidateStruct(obj interface{}) error {
  14. if kindOfData(obj) == reflect.Struct {
  15. v.lazyinit()
  16. if err := v.validate.Struct(obj); err != nil {
  17. return err
  18. }
  19. }
  20. return nil
  21. }
  22. func (v *DefaultValidator) Engine() interface{} {
  23. v.lazyinit()
  24. return v.validate
  25. }
  26. func (v *DefaultValidator) lazyinit() {
  27. v.once.Do(func() {
  28. v.validate = validator.New()
  29. v.validate.SetTagName("validate")
  30. _ = v.validate.RegisterValidation("phone", phone)
  31. _ = v.validate.RegisterValidation("idcard", idcard)
  32. _ = v.validate.RegisterValidation("chinesename", chinesename)
  33. })
  34. }
  35. func kindOfData(data interface{}) reflect.Kind {
  36. value := reflect.ValueOf(data)
  37. valueType := value.Kind()
  38. if valueType == reflect.Ptr {
  39. valueType = value.Elem().Kind()
  40. }
  41. return valueType
  42. }