topfans/backend/pkg/validator/validator.go

92 lines
2.0 KiB
Go

package validator
import (
"regexp"
"strings"
"github.com/topfans/backend/pkg/filter"
)
const (
// MinPasswordLength 最小密码长度
MinPasswordLength = 6
// MaxPasswordLength 最大密码长度
MaxPasswordLength = 50
// MinNicknameLength 最小昵称长度
MinNicknameLength = 2
// MaxNicknameLength 最大昵称长度
MaxNicknameLength = 20
)
var (
// 中国手机号正则表达式
mobileRegex = regexp.MustCompile(`^1[3-9]\d{9}$`)
// 昵称正则:中文、英文、数字、下划线,首字符不能是数字或下划线
nicknameRegex = regexp.MustCompile(`^[一-龥a-zA-Z][一-龥a-zA-Z0-9_]*$`)
)
// ValidateMobile 验证手机号格式
func ValidateMobile(mobile string) bool {
if mobile == "" {
return false
}
return mobileRegex.MatchString(mobile)
}
// ValidatePassword 验证密码强度
func ValidatePassword(password string) (bool, string) {
if password == "" {
return false, "password cannot be empty"
}
if len(password) < MinPasswordLength {
return false, "password too short"
}
if len(password) > MaxPasswordLength {
return false, "password too long"
}
return true, ""
}
// ValidateNickname 验证昵称
func ValidateNickname(nickname string) (bool, string) {
if nickname == "" {
return false, "nickname cannot be empty"
}
nickname = strings.TrimSpace(nickname)
// 使用 rune 计数,支持中文等多字节字符
runeCount := len([]rune(nickname))
if runeCount < MinNicknameLength {
return false, "nickname too short"
}
if runeCount > MaxNicknameLength {
return false, "nickname too long"
}
// 格式校验:中文、英文、数字、下划线,首字符不能是数字或下划线
if !nicknameRegex.MatchString(nickname) {
return false, "invalid nickname format"
}
// 敏感词校验
if filter.GetDefault().Contains(nickname) {
return false, "nickname contains sensitive words"
}
return true, ""
}
// ValidateStarID 验证star_id
func ValidateStarID(starID int64) bool {
return starID > 0
}
// ValidateUserID 验证user_id
func ValidateUserID(userID int64) bool {
return userID > 0
}