73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package utils
|
||
|
||
import (
|
||
"regexp"
|
||
"strings"
|
||
)
|
||
|
||
// Validator 验证器
|
||
type Validator struct{}
|
||
|
||
// IsEmail 验证邮箱格式
|
||
func (v *Validator) IsEmail(email string) bool {
|
||
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
|
||
matched, _ := regexp.MatchString(pattern, email)
|
||
return matched
|
||
}
|
||
|
||
// IsPhone 验证手机号格式
|
||
func (v *Validator) IsPhone(phone string) bool {
|
||
pattern := `^1[3-9]\d{9}$`
|
||
matched, _ := regexp.MatchString(pattern, phone)
|
||
return matched
|
||
}
|
||
|
||
// IsUsername 验证用户名格式
|
||
func (v *Validator) IsUsername(username string) bool {
|
||
// 用户名只能包含字母、数字、下划线,长度3-20
|
||
pattern := `^[a-zA-Z0-9_]{3,20}$`
|
||
matched, _ := regexp.MatchString(pattern, username)
|
||
return matched
|
||
}
|
||
|
||
// IsPassword 验证密码强度
|
||
func (v *Validator) IsPassword(password string) bool {
|
||
// 密码至少6位,包含字母和数字
|
||
if len(password) < 6 {
|
||
return false
|
||
}
|
||
|
||
hasLetter := regexp.MustCompile(`[a-zA-Z]`).MatchString(password)
|
||
hasNumber := regexp.MustCompile(`[0-9]`).MatchString(password)
|
||
|
||
return hasLetter && hasNumber
|
||
}
|
||
|
||
// IsURL 验证URL格式
|
||
func (v *Validator) IsURL(url string) bool {
|
||
pattern := `^https?://[^\s/$.?#].[^\s]*$`
|
||
matched, _ := regexp.MatchString(pattern, url)
|
||
return matched
|
||
}
|
||
|
||
// IsEmpty 检查字符串是否为空
|
||
func (v *Validator) IsEmpty(str string) bool {
|
||
return strings.TrimSpace(str) == ""
|
||
}
|
||
|
||
// IsValidRole 验证角色名称
|
||
func (v *Validator) IsValidRole(role string) bool {
|
||
validRoles := []string{"admin", "user", "guest"}
|
||
for _, validRole := range validRoles {
|
||
if role == validRole {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// NewValidator 创建验证器实例
|
||
func NewValidator() *Validator {
|
||
return &Validator{}
|
||
}
|