validate.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package util
  2. import (
  3. "errors"
  4. "regexp"
  5. "unicode"
  6. "github.com/go-sql-driver/mysql"
  7. )
  8. var (
  9. emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)
  10. phoneRegex = regexp.MustCompile(`^\+?[1-9]\d{6,14}$`)
  11. )
  12. func IsValidEmail(email string) bool {
  13. return emailRegex.MatchString(email)
  14. }
  15. func IsValidPhone(phone string) bool {
  16. return phoneRegex.MatchString(phone)
  17. }
  18. // ValidatePassword 校验密码强度:至少 8 位,且包含大写字母、小写字母和数字。
  19. func ValidatePassword(password string) string {
  20. if len(password) < 8 {
  21. return "密码长度不能少于8个字符"
  22. }
  23. if len(password) > 72 {
  24. return "密码长度不能超过72个字符"
  25. }
  26. var hasUpper, hasLower, hasDigit bool
  27. for _, c := range password {
  28. switch {
  29. case unicode.IsUpper(c):
  30. hasUpper = true
  31. case unicode.IsLower(c):
  32. hasLower = true
  33. case unicode.IsDigit(c):
  34. hasDigit = true
  35. }
  36. }
  37. if !hasUpper || !hasLower || !hasDigit {
  38. return "密码必须包含大写字母、小写字母和数字"
  39. }
  40. return ""
  41. }
  42. // IsDuplicateEntryErr 判断是否为 MySQL 唯一索引冲突错误 (errno 1062)。
  43. func IsDuplicateEntryErr(err error) bool {
  44. var me *mysql.MySQLError
  45. return errors.As(err, &me) && me.Number == 1062
  46. }
  47. func NormalizePage(page, pageSize int64) (int64, int64) {
  48. if page <= 0 {
  49. page = 1
  50. }
  51. if pageSize <= 0 {
  52. pageSize = 20
  53. }
  54. if pageSize > 100 {
  55. pageSize = 100
  56. }
  57. return page, pageSize
  58. }