validator.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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("chinesePhone", chinesePhone)
  31. _ = v.validate.RegisterValidation("isoPhone", isoPhone)
  32. _ = v.validate.RegisterValidation("idCard", idCard)
  33. _ = v.validate.RegisterValidation("chineseName", chineseName)
  34. })
  35. }
  36. func kindOfData(data interface{}) reflect.Kind {
  37. value := reflect.ValueOf(data)
  38. valueType := value.Kind()
  39. if valueType == reflect.Ptr {
  40. valueType = value.Elem().Kind()
  41. }
  42. return valueType
  43. }