Go语言常用数据格式校验工具:高效验证QQ、手机、邮箱、用户名和密码
前言
在开发用户注册、登录系统时,数据格式校验是必不可少的一环。合理的校验机制不仅能提升系统安全性,还能改善用户体验。本文将分享一套实用的数据格式校验工具,可直接集成到你的项目中。
一、完整的校验工具代码
// 预编译正则表达式(全局变量,程序启动时编译一次)
var (
qqRegex = regexp.MustCompile(`^\d{5,11}$`)
phoneRegex = regexp.MustCompile(`^1\d{10}$`)
emailRegex = regexp.MustCompile(`^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$`)
usernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_-]{5,20}$`)
// 密码校验相关正则(拆分以兼容Go语法)
lowercaseRegex = regexp.MustCompile(`[a-z]`)
uppercaseRegex = regexp.MustCompile(`[A-Z]`)
digitRegex = regexp.MustCompile(`\d`)
specialRegex = regexp.MustCompile(`[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?` + "`" + `~]`)
passwordLengthRegex = regexp.MustCompile(`^.{6,20}$`)
// 常见弱密码列表
weakPasswords = map[string]bool{
"12345678": true,
"password": true,
"qwertyui": true,
"abc123456": true,
"11111111": true,
"123456789": true,
"1234567890": true,
"88888888": true,
}
// 修复连续字符正则:Go中需要使用双反斜杠转义反向引用
consecutiveCharsRegex = regexp.MustCompile(`(.)\\1{3,}`)
// 序列字符正则
sequenceCharsRegex = regexp.MustCompile(`(0123|1234|2345|3456|4567|5678|6789|7890|abcde|fghij|klmno|pqrst|uvwxy|zabcde|ABCDE|FGHIJ|KLMNO|PQRST|UVWXY|ZABCDE)`)
)
// IsValidQQ 校验QQ号格式是否合法
func IsValidQQ(qq string) bool {
return qqRegex.MatchString(qq)
}
// IsValidPhone 校验手机号格式是否合法
func IsValidPhone(phone string) bool {
return phoneRegex.MatchString(phone)
}
// IsValidEmail 校验邮箱格式是否合法
func IsValidEmail(email string) bool {
return emailRegex.MatchString(email)
}
// IsValidUsername 校验用户名格式是否合法
func IsValidUsername(username string) bool {
return usernameRegex.MatchString(username)
}
// IsValidPassword 校验密码格式是否合法
func IsValidPassword(password string) bool {
// 1. 检查长度
if !passwordLengthRegex.MatchString(password) {
return false
}
// 2. 检查字符类型组合(至少三种)
typeCount := 0
if lowercaseRegex.MatchString(password) {
typeCount++
}
if uppercaseRegex.MatchString(password) {
typeCount++
}
if digitRegex.MatchString(password) {
typeCount++
}
if specialRegex.MatchString(password) {
typeCount++
}
if typeCount < 3 {
return false
}
// 3. 检查是否为常见弱密码
if weakPasswords[password] {
return false
}
// 4. 检查是否包含连续重复字符
if consecutiveCharsRegex.MatchString(password) {
return false
}
// 5. 检查是否包含常见序列
if sequenceCharsRegex.MatchString(password) {
return false
}
return true
}
// GetPasswordErrorMsg 返回密码校验失败的具体原因
func GetPasswordErrorMsg(password string) string {
if len(password) < 6 {
return "密码长度不能少于6位"
}
if len(password) > 20 {
return "密码长度不能超过20位"
}
// 检查字符类型组合
typeCount := 0
if lowercaseRegex.MatchString(password) {
typeCount++
}
if uppercaseRegex.MatchString(password) {
typeCount++
}
if digitRegex.MatchString(password) {
typeCount++
}
if specialRegex.MatchString(password) {
typeCount++
}
if typeCount < 3 {
return "密码需包含大小写字母、数字和特殊字符中的至少三种"
}
if weakPasswords[password] {
return "密码过于简单,容易被破解"
}
if consecutiveCharsRegex.MatchString(password) {
return "密码不能包含连续4个以上相同字符"
}
if sequenceCharsRegex.MatchString(password) {
return "密码不能包含常见连续序列(如123456、abcdef)"
}
return "密码格式不合法"
}
二、使用示例
func main() {
// QQ号校验
fmt.Println("QQ号校验:")
fmt.Println("12345:", IsValidQQ("12345")) // true
fmt.Println("1234:", IsValidQQ("1234")) // false
// 手机号校验
fmt.Println("\n手机号校验:")
fmt.Println("13800138000:", IsValidPhone("13800138000")) // true
fmt.Println("1380013800:", IsValidPhone("1380013800")) // false
// 邮箱校验
fmt.Println("\n邮箱校验:")
fmt.Println("test@example.com:", IsValidEmail("test@example.com")) // true
fmt.Println("test@com:", IsValidEmail("test@com")) // false
// 用户名校验
fmt.Println("\n用户名校验:")
fmt.Println("user_123:", IsValidUsername("user_123")) // true
fmt.Println("usr:", IsValidUsername("usr")) // false
// 密码校验
fmt.Println("\n密码校验:")
fmt.Println("Abc123!@#:", IsValidPassword("Abc123!@#")) // true
fmt.Println("123456:", IsValidPassword("123456")) // false
// 密码错误信息
fmt.Println("\n密码错误信息:")
fmt.Println("123:", GetPasswordErrorMsg("123")) // 密码长度不能少于6位
fmt.Println("12345678:", GetPasswordErrorMsg("12345678")) // 密码需包含大小写字母、数字和特殊字符中的至少三种
}
三、实际调用
if !utils.IsValidPassword(dto.NewPassword) {
errMsg := utils.GetPasswordErrorMsg(dto.NewPassword)
result.FailedWithMsg(c, result.BadRequest, errMsg)
return
}
四、功能特点
1. 预编译优化
所有正则表达式在程序启动时预编译,提升运行时效率。
2. 全面的校验覆盖
- QQ号: 5-11位纯数字
- 手机号: 11位数字,1开头
- 邮箱: 标准邮箱格式验证
- 用户名: 5-20位,支持字母、数字、下划线、连字符
- 密码: 多重安全策略校验
3. 密码强度多层次检测
- 长度要求(6-20位)
- 字符类型组合(至少三种)
- 弱密码黑名单过滤
- 连续字符检测
- 序列模式识别
4. 友好的错误提示
提供具体的密码错误原因,帮助用户快速修正。
五、应用场景
该工具适用于:
- 用户注册系统:验证用户输入信息的合法性
- 密码修改功能:确保新密码符合安全要求
- 数据导入清洗:预处理外部数据
- API接口验证:请求参数格式校验
- 安全审计:定期检查用户密码强度
结语
这套校验工具经过实际项目验证,在安全性和用户体验之间取得了良好平衡。代码结构清晰,易于扩展和维护,可以直接集成到你的Go项目中。
欢迎点赞收藏,如有问题请在评论区留言讨论!