package util import ( "errors" "regexp" "unicode" "github.com/go-sql-driver/mysql" ) var ( emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`) phoneRegex = regexp.MustCompile(`^\+?[1-9]\d{6,14}$`) ) func IsValidEmail(email string) bool { return emailRegex.MatchString(email) } func IsValidPhone(phone string) bool { return phoneRegex.MatchString(phone) } // ValidatePassword 校验密码强度:至少 8 位,且包含大写字母、小写字母和数字。 func ValidatePassword(password string) string { if len(password) < 8 { return "密码长度不能少于8个字符" } if len(password) > 72 { return "密码长度不能超过72个字符" } var hasUpper, hasLower, hasDigit bool for _, c := range password { switch { case unicode.IsUpper(c): hasUpper = true case unicode.IsLower(c): hasLower = true case unicode.IsDigit(c): hasDigit = true } } if !hasUpper || !hasLower || !hasDigit { return "密码必须包含大写字母、小写字母和数字" } return "" } // IsDuplicateEntryErr 判断是否为 MySQL 唯一索引冲突错误 (errno 1062)。 func IsDuplicateEntryErr(err error) bool { var me *mysql.MySQLError return errors.As(err, &me) && me.Number == 1062 } func NormalizePage(page, pageSize int64) (int64, int64) { if page <= 0 { page = 1 } if pageSize <= 0 { pageSize = 20 } if pageSize > 100 { pageSize = 100 } return page, pageSize }