tianyuan-api-server/apps/gateway/internal/validator/validator.go
2024-10-02 00:57:17 +08:00

73 lines
1.5 KiB
Go

// internal/validator/validation.go
package validator
import (
"errors"
"fmt"
"github.com/zeromicro/go-zero/core/stores/redis"
"regexp"
"unicode/utf8"
)
func ValidateUsername(username string) error {
if utf8.RuneCountInString(username) < 2 {
return errors.New("用户名长度不能少于2个中文或4个英文字符")
}
return nil
}
func ValidatePassword(password string) error {
if len(password) < 8 {
return errors.New("密码长度不能少于8位")
}
return nil
}
func ValidatePhoneNumber(phone string) error {
phoneRegex := `^1[3-9]\d{9}$`
re := regexp.MustCompile(phoneRegex)
if !re.MatchString(phone) {
return errors.New("手机号格式不正确")
}
return nil
}
func ValidateVerifyCode(redisClient *redis.Redis, phone, code string) error {
// 从 Redis 获取验证码
savedCode, err := redisClient.Get(phone)
if err != nil {
if errors.Is(err, redis.Nil) {
return errors.New("验证码已过期")
}
return err
}
// 验证码不匹配
if savedCode != code {
return errors.New("验证码不正确")
}
return nil
}
func IsValidIPAddress(ip string) bool {
// 正则表达式:匹配 IPv4 地址格式
var ipRegex = regexp.MustCompile(`^([0-9]{1,3}\.){3}[0-9]{1,3}$`)
// 判断格式是否匹配
if !ipRegex.MatchString(ip) {
return false
}
// 验证每个段是否在 0 到 255 之间
var segments = ipRegex.FindStringSubmatch(ip)
for _, segment := range segments {
var num int
fmt.Sscanf(segment, "%d", &num)
if num < 0 || num > 255 {
return false
}
}
return true
}