
文章插圖
在用戶提交郵箱地址以后我們需要驗(yàn)證用戶郵箱地址是否合法,解決方案的范圍很廣,可以通過使用正則表達(dá)式來檢查電子郵件地址的格式是否正確,甚至可以通過嘗試與遠(yuǎn)程服務(wù)器進(jìn)行交互來解決問題 。兩者之間也有一些中間立場,例如檢查頂級域是否具有有效的MX記錄以及檢測臨時(shí)電子郵件地址 。
一種確定的方法是向該地址發(fā)送電子郵件,并讓用戶單擊鏈接進(jìn)行確認(rèn) 。但是在發(fā)送文章之前我們需要對用戶的郵箱進(jìn)行預(yù)定義檢測 。
簡單版本:正則表達(dá)式基于W3C的正則表達(dá)式,此代碼檢查電子郵件地址的結(jié)構(gòu) 。
package mainimport ("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 examplee := "test@golangcode.com"if isEmailValid(e) {fmt.Println(e + " is a valid email")}// Invalid exampleif !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查找在此示例中,我們結(jié)合了對電子郵件地址進(jìn)行正則表達(dá)式檢查的快速速度和更可靠的MX記錄查找 。這意味著,如果電子郵件的域部分不存在,或者該域不接受電子郵件,它將被標(biāo)記為無效 。
作為net軟件包的一部分,我們可以使用LookupMX為我們做額外的查找 。
package mainimport ("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 domainif e := "test@golangcode-example.com"; !isEmailValid(e) {fmt.Println(e + " is not a valid email")}// Real domainif 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}
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問題,請您及時(shí)就醫(yī)或請專業(yè)人士給予相關(guān)指導(dǎo)!
「愛刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對您有所幫助:- outlook郵箱服務(wù)器設(shè)置 outlook無法登陸服務(wù)器
- 免費(fèi)注冊企業(yè)郵箱 網(wǎng)易企業(yè)免費(fèi)郵箱登陸
- 網(wǎng)易免費(fèi)郵箱注冊條件 網(wǎng)易郵箱注冊失敗是怎么回事
- 辦理手機(jī)號卡應(yīng)注意什么 辦理手機(jī)卡要注意什么
- 手機(jī)號更換8元保號套餐,取消最低消費(fèi),親測成功 聯(lián)通怎么改8元最低消費(fèi)套餐
- Foxmail7.2郵箱如何轉(zhuǎn)移備份郵件 foxmail郵件導(dǎo)出備份
- 阿里云企業(yè)郵箱收費(fèi)標(biāo)準(zhǔn) 云企業(yè)郵箱是什么
- 農(nóng)行信用卡如何修改預(yù)留的手機(jī)號碼? 怎么樣修改銀行卡預(yù)留手機(jī)號碼
- 怎么通過手機(jī)號碼找到對方的位置? 怎么用手機(jī)號查一個(gè)人的位置
- 怎么申請開通注冊郵箱賬號? 如何創(chuàng)建自己的電子郵件
