我检查了 StackOverflow,但找不到任何可以回答的问题如何用 Go 语言验证电子邮件.
经过一番研究,我根据自己的需要找出并解决了这个问题。
我有这个regex and 转函数,效果很好:
import (
"fmt"
"regexp"
)
func main() {
fmt.Println(isEmailValid("[email protected] /cdn-cgi/l/email-protection")) // true
fmt.Println(isEmailValid("[email protected] /cdn-cgi/l/email-protection")) // true -- expected "false"
}
// isEmailValid checks if the email provided is valid by regex.
func isEmailValid(e string) bool {
emailRegex := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
return emailRegex.MatchString(e)
}
问题是它接受我不想要的特殊字符。我尝试使用其他语言的“正则表达式”表达式中的一些,但它引发了错误《未知的逃脱》在调试中。
谁能给我一个好的正则表达式或任何与 GoLang 一起使用的快速解决方案(pkg)?
标准库内置了电子邮件解析和验证,只需使用:mail.ParseAddress() https://golang.org/pkg/net/mail/#ParseAddress.
一个简单的“有效”测试:
func valid(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
测试它:
for _, email := range []string{
"[email protected] /cdn-cgi/l/email-protection",
"bad-example",
} {
fmt.Printf("%18s valid: %t\n", email, valid(email))
}
哪个输出(尝试一下去游乐场 https://play.golang.org/p/MjOg6JWkfd6):
[email protected] /cdn-cgi/l/email-protection valid: true
bad-example valid: false
NOTE:
The net/mail https://pkg.go.dev/net/mail包实现并遵循RFC 5322 https://www.rfc-editor.org/rfc/rfc5322规范(以及扩展RFC 6532 https://www.rfc-editor.org/rfc/rfc6532.html)。这意味着看似错误的电子邮件地址,例如bad-example@t
被包接受并解析,因为它根据规范是有效的。t
可以是有效的本地域名,但不一定是公共域名。net/mail
不检查地址的域部分是否是公共域,也不检查它是否是现有的、可访问的公共域。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)