在用戶提交郵箱地址以後我們需要驗證用戶郵箱地址是否合法,解決方案的範圍很廣,可以通過使用正則表達式來檢查電子郵件地址的格式是否正確,甚至可以通過嘗試與遠程服務器進行交互來解決問題。兩者之間也有一些中間立場,例如檢查頂級域是否具有有效的MX記錄以及檢測臨時電子郵件地址。
一種確定的方法是向該地址發送電子郵件,並讓用戶單擊鏈接進行確認。但是在發送文章之前我們需要對用戶的郵箱進行預定義檢測。
簡單版本:正則表達式
基於W3C的正則表達式,此代碼檢查電子郵件地址的結構。
package main
import (
"fmt"
"regexp"
)
var 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])?)*$")
func main() {
// Valid example
e := "test@golangcode.com"
if isEmailValid(e) {
fmt.Println(e + " is a valid email")
}
// Invalid example
if !isEmailValid("just text") {
fmt.Println("not a valid email")
}
}
// isEmailValid checks if the email provided passes the required structure and length.
func isEmailValid(e string) bool {
if len(e) < 3 && len(e) > 254 {
return false
}
return emailRegex.MatchString(e)
}
稍微更好的解決方案:Regex + MX查找
在此示例中,我們結合了對電子郵件地址進行正則表達式檢查的快速速度和更可靠的MX記錄查找。這意味着,如果電子郵件的域部分不存在,或者該域不接受電子郵件,它將被標記為無效。
作為net軟件包的一部分,我們可以使用LookupMX為我們做額外的查找。
package main
import (
"fmt"
"net"
"regexp"
"strings"
)
var 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])?)*$")
func main() {
// Made-up domain
if e := "test@golangcode-example.com"; !isEmailValid(e) {
fmt.Println(e + " is not a valid email")
}
// Real domain
if e := "test@google.com"; !isEmailValid(e) {
fmt.Println(e + " not a valid email")
}
}
// isEmailValid checks if the email provided passes the required structure
// and length test. It also checks the domain has a valid MX record.
func isEmailValid(e string) bool {
if len(e) < 3 && len(e) > 254 {
return false
}
if !emailRegex.MatchString(e) {
return false
}
parts := strings.Split(e, "@")
mx, err := net.LookupMX(parts[1])
if err != nil || len(mx) == 0 {
return false
}
return true
}
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/235166.html
微信掃一掃
支付寶掃一掃