雖然正則表達式可一行完成,但 ASP 經典環境常使用純 VBScript 邏輯逐字元檢查。本函數 IsValidEmail(email) 實作完整語法規則:單一 @、本地部/域部非空、允許字元集、不以點開頭結尾、域部至少一個點且頂級域長度 2-3 碼、禁止連續雙點。
Function IsValidEmail(email)
Dim names, name, i, c
IsValidEmail = True
' 必須有且只有一個 @
names = Split(email, "@")
If UBound(names) <> 1 Then
IsValidEmail = False
Exit Function
End If
For Each name In names
' 本地部/域部不可為空
If Len(name) <= 0 Then
IsValidEmail = False
Exit Function
End If
' 逐字元檢查允許字元:字母、數字、_ - .
For i = 1 To Len(name)
c = LCase(Mid(name, i, 1))
If InStr("abcdefghijklmnopqrstuvwxyz_-.", c) <= 0 And Not IsNumeric(c) Then
IsValidEmail = False
Exit Function
End If
Next
' 不得以 . 開頭或結尾
If Left(name, 1) = "." Or Right(name, 1) = "." Then
IsValidEmail = False
Exit Function
End If
Next
' 域部至少一個點
If InStr(names(1), ".") <= 0 Then
IsValidEmail = False
Exit Function
End If
' 頂級域長度 2 或 3 (如 .com .net .tw .org .info 需擴充)
i = Len(names(1)) - InStrRev(names(1), ".")
If i <> 2 And i <> 3 Then
IsValidEmail = False
Exit Function
End If
' 禁止連續雙點
If InStr(email, "..") > 0 Then IsValidEmail = False
End Function
Dim testEmails, e
testEmails = Array("user@example.com", "user.name@sub.domain.org", "invalid@", "@nodomain.com", "user@.com", "user@domain.c", "user..name@domain.com")
For Each e In testEmails
Response.Write e & " = " & IsValidEmail(e) & "
"
Next
Function IsValidEmailRegex(email)
Dim re
Set re = New RegExp
re.IgnoreCase = True
re.Global = False
' 簡易 RFC 5322 子集
re.Pattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
IsValidEmailRegex = re.Test(email)
Set re = Nothing
End Function
{2,}。<input type="email"> 可先行攔截明顯錯誤,後端仍需驗證。