validate.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package util
  2. import (
  3. "regexp"
  4. "unicode"
  5. )
  6. var (
  7. emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)
  8. phoneRegex = regexp.MustCompile(`^\+?[1-9]\d{6,14}$`)
  9. )
  10. func IsValidEmail(email string) bool {
  11. return emailRegex.MatchString(email)
  12. }
  13. func IsValidPhone(phone string) bool {
  14. return phoneRegex.MatchString(phone)
  15. }
  16. // ValidatePassword 校验密码强度:至少 8 位,且包含大写字母、小写字母和数字。
  17. func ValidatePassword(password string) string {
  18. if len(password) < 8 {
  19. return "密码长度不能少于8个字符"
  20. }
  21. if len(password) > 72 {
  22. return "密码长度不能超过72个字符"
  23. }
  24. var hasUpper, hasLower, hasDigit bool
  25. for _, c := range password {
  26. switch {
  27. case unicode.IsUpper(c):
  28. hasUpper = true
  29. case unicode.IsLower(c):
  30. hasLower = true
  31. case unicode.IsDigit(c):
  32. hasDigit = true
  33. }
  34. }
  35. if !hasUpper || !hasLower || !hasDigit {
  36. return "密码必须包含大写字母、小写字母和数字"
  37. }
  38. return ""
  39. }
  40. func NormalizePage(page, pageSize int64) (int64, int64) {
  41. if page <= 0 {
  42. page = 1
  43. }
  44. if pageSize <= 0 {
  45. pageSize = 20
  46. }
  47. if pageSize > 100 {
  48. pageSize = 100
  49. }
  50. return page, pageSize
  51. }