如何在Go中验证电子邮件地址

我检查了 StackOverflow 并找不到任何可以回答如何在 Go Language 中验证电子邮件的问题。

经过一番研究,我想出了并根据我的需要解决了它。

我有这个正则表达式Go 函数,它工作正常:

import (
    "fmt"
    "regexp"
)

func main() {
    fmt.Println(isEmailValid("test44@gmail.com")) // true
    fmt.Println(isEmailValid("test$@gmail.com")) // 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()

一个简单的“有效”测试:

func valid(email string) bool {
    _, err := mail.ParseAddress(email)
    return err == nil
}

测试它:

for _, email := range []string{
    "good@exmaple.com",
    "bad-example",
} {
    fmt.Printf("%18s valid: %tn", email, valid(email))
}

哪些输出(在Go Playground上试试):

  good@exmaple.com valid: true
       bad-example valid: false

  • Thanks for that, it's working on most of the cases. Still, I have some issues with the following invalid emails:
    "email@example.com (Joe Smith)",
    "email@example"
  • @RiyazKhan `example` is a valid domain, just like `example.com`. It does not necessarily have to designate a public domain, it may be a local domain of a local network. As to the `(Joe Smith)` part: it's a comment and it may be anywhere in the email, see [Wikipedia: Email address](https://en.wikipedia.org/wiki/Email_address). Trust me, the `net/mail` package can parse email addresses better, faster and more reliably than your custom solution can.

以上是如何在Go中验证电子邮件地址的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>