如何在JavaScript中驗證電子郵件地址

有很多方法可以驗證電子郵件地址。使用普通的JavaScript學習正確的方法,並找出所有可用的選項

電子郵件地址的驗證是處理表單時的常見操作之一。

在聯繫表格,註冊和登錄表格等中很有用。

有人建議你不應該驗證電子郵件完全沒有。我認為稍微驗證一下會更好,但不要太過熱情。

電子郵件驗證應遵循哪些規則?

電子郵件地址由本地部分和域部分兩部分組成。

本地部分可以包含

  • 任何字母數字字符:a-zA-Z0-9
  • 標點:"(),:;<>@[\]
  • 特殊的角色:!#$%&'*+-/=?^_{|}~
  • 一個點.,如果它不是第一個或最後一個字符。而且,它不能重複

域部分可以包含

  • 任何字母數字字符:a-zA-Z0-9
  • 連字符-,如果它不是第一個或最後一個字符。可以重複

使用正則表達式

驗證電子郵件地址的最佳選擇是使用正則表達式

沒有普遍的電子郵件支票正則表達式。每個人似乎使用的都是不同的,由於不准確或由於他們不計算引入的較新域或國際化的電子郵件地址,您在網上找到的大多數正則表達式將無法通過最基本的電子郵件方案

不要盲目使用任何正則表達式,而要先檢查一下。

我做了這個例子在毛刺它將檢查被視為對正則表達式有效的電子郵件地址列表。您可以更改正則表達式並將其與您要使用的其他正則表達式進行比較。

當前添加的是我認為最準確的一個,對其進行了稍微編輯以修正帶有多個點的問題。

注意:我沒有提出。我在Quora答案中找到了它,但是我不確定那是原始來源。

這是一個使用該正則表達式進行驗證的函數:

const validate = (email) => {
  const expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i

return expression.test(String(email).toLowerCase()) }

滿足所有常見情況,可以假設人們將添加的99.9%的電子郵件地址已成功驗證。

此故障的代碼包含其他正則表達式,您可以通過重新混合項目輕鬆地嘗試。

儘管非常準確,但是此正則表達式在一些極端情況下存在一些問題,您可以根據需要使用(或不使用)這些正則表達式。

錯誤的否定地址,例如:

"very.(),:;<>[]".VERY."[email protected]\ "very".unusual"@strange.example.com

one.“more\ long”@example.website.place

本地地址的假否定:

[email protected]
[email protected]

of little use in publicly accessible websites (actually a plus in publicly accessible websites to have those denied)

Also, false negative for IP-based emails:

[email protected][2001:DB8::1]
[email protected]

There is a false positive for addresses with the local part too long:

123[email protected]example.com

Do you want a simpler regex?

The above regex is very complicated, to the point I won’t even try to understand it. Regular expressions masters created it, and it spread through the Internet until I found it.

Using it at this point is a matter of copy/pasting it.

A much simpler solution is just to check that the address entered contains something, then an @ symbol, and then something else.

In this case, this regex will do the trick:

const expression = /\[email protected]\S+/
expression.test(String('[email protected]').toLowerCase())

This will cause many false positives, but after all the ultimate test on an email address validity happens when you ask the user to click something in the email to confirm the address, and I’d rather try to send to an invalid email than reject a valid email because of an error in my regex.

This is listed in the above Glitch, so you can easily try it.

Validate the HTML field directly

HTML5 provided us the email field type, so don’t forget you can also validate emails using that:

<input type="email" name="email" placeholder="Your email" />

Depending on the browser implementation also this validation will give you different results.

This Glitch shows the same emails I tested the regex with, and their result when validated through the HTML form.

The results are interesting, and here as well we have invalid emails that pass, and valid emails that don’t. Our regex actually does a more accurate job than the HTML filtering built into the browser.

Validate server-side

If your app has a server, the server needs to validate the email as well, because you can never trust client code, and also JavaScript might be disabled on the user browser.

Using Node.js you have the advantage of being able to reuse the frontend code as-is. In this case the function that validates can work both client-side and server-side.

You can also use pre-made packages like isemail, but also in this case results vary. Here is the isemail benchmark on the same emails we used above: https://glitch.com/edit/#!/flavio-email-validation-node-isemail


More js tutorials: