修复邮箱地址格式校验
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-06 05:17:13 +08:00
1 parent 8f13ab976c
commit b96cc4937d
2 files changed
+43 -4

No files matched your search

+22 -4
View File
@@ -1,12 +1,30 @@
package address
import "strings"
import (
"net/mail"
"strings"
)
// IsValidEmailAddress 检查是否是有效的邮箱地址
func IsValidEmailAddress(str string) bool {
ars := strings.Split(str, "@")
if len(ars) != 2 {
parsed, err := mail.ParseAddress(str)
if err != nil || parsed.Address != str {
return false
}
return strings.Contains(ars[1], ".")
separator := strings.LastIndexByte(str, '@')
if separator <= 0 || separator == len(str)-1 {
return false
}
localPart := str[:separator]
domain := str[separator+1:]
if strings.Contains(localPart, "..") || strings.HasPrefix(localPart, ".") || strings.HasSuffix(localPart, ".") {
return false
}
if strings.Contains(domain, "..") || strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") {
return false
}
return strings.Contains(domain, ".")
}
+21
View File
@@ -40,3 +40,24 @@ func TestIsValidEmailAddress(t *testing.T) {
})
}
}
func TestIsValidEmailAddressRejectsMalformedAddresses(t *testing.T) {
invalid := []string{
"@example.com",
"user@",
"user..name@example.com",
"user@example..com",
"user name@example.com",
"User <user@example.com>",
" user@example.com",
"user@example.com ",
".user@example.com",
"user.@example.com",
"user@example.com.",
}
for _, value := range invalid {
if IsValidEmailAddress(value) {
t.Errorf("IsValidEmailAddress(%q) = true, want false", value)
}
}
}