47 lines
1.0 KiB
Go
47 lines
1.0 KiB
Go
|
|
package utils
|
||
|
|
|
||
|
|
import (
|
||
|
|
"regexp"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
// ValidateEmail 验证邮箱
|
||
|
|
func ValidateEmail(email string) bool {
|
||
|
|
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
|
||
|
|
matched, _ := regexp.MatchString(pattern, email)
|
||
|
|
return matched
|
||
|
|
}
|
||
|
|
|
||
|
|
// ValidateUsername 验证用户名
|
||
|
|
func ValidateUsername(username string) bool {
|
||
|
|
if len(username) < 3 || len(username) > 30 {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
pattern := `^[a-zA-Z0-9_]+$`
|
||
|
|
matched, _ := regexp.MatchString(pattern, username)
|
||
|
|
return matched
|
||
|
|
}
|
||
|
|
|
||
|
|
// ValidatePassword 验证密码强度
|
||
|
|
func ValidatePassword(password string) bool {
|
||
|
|
if len(password) < 6 || len(password) > 50 {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
|
||
|
|
// ValidatePhone 验证手机号
|
||
|
|
func ValidatePhone(phone string) bool {
|
||
|
|
pattern := `^1[3-9]\d{9}$`
|
||
|
|
matched, _ := regexp.MatchString(pattern, phone)
|
||
|
|
return matched
|
||
|
|
}
|
||
|
|
|
||
|
|
// SanitizeHTML 清理HTML
|
||
|
|
func SanitizeHTML(input string) string {
|
||
|
|
// 简单实现,实际使用建议用专门库
|
||
|
|
input = strings.ReplaceAll(input, "<", "<")
|
||
|
|
input = strings.ReplaceAll(input, ">", ">")
|
||
|
|
return input
|
||
|
|
}
|