Check if a E-Mail adress is valid

A simple function to test if a E-Mail adress is valid.

' Made by using VBScript version 5.6 
Private Function IsEmailValid(byVal EmailAddress)
    Dim TestEmailAddress, RegularExpressionObject, ExpressionMatch
 
    ' Convert to string and trim whitespace
    TestEmailAddress = CStr( EmailAddress )
    TestEmailAddress = Trim( TestEmailAddress )
 
    ' Check if the given E-Mail adress is empty
    If TestEmailAddress = "" Then
        IsEmailValid = False
        Exit Function
    End If
 
     ' Minimum 6 characters... (a@b.de)
    if len(TestEmailAddress) < 6 Then
        IsEmailValid = False
        Exit Function
    End If
 
    ' Test the E-Mail adress with a regular expression
    ' (RegExp from regexlib.com - made by David Lott)
    Set RegularExpressionObject = New RegExp
 
    With RegularExpressionObject
        .Global = True
        .IgnoreCase = True
        .Pattern = "^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$"
    End With
 
    ExpressionMatch = RegularExpressionObject.Test(TestEmailAddress)
 
    ' Does the RegExp match?
    If Not ExpressionMatch Then
        IsEmailValid = False
        Exit Function
    End If
 
    ' Cleanup
    Set RegularExpressionObject = Nothing
    Set ExpressionMatch = Nothing
 
     ' Congrats, the E-Mail adress is valid 
    IsEmailValid = True
End Function
 
 ' IsEmailValid returns true
Response.Write IsEmailValid("test@example.com")
Response.Write IsEmailValid("t@example.com")
Response.Write IsEmailValid("404@example.org")
Response.Write IsEmailValid("test@example.jp")
Response.Write IsEmailValid("test.adress@example.com")
 
 
 ' IsEmailValid returns false
Response.Write IsEmailValid("")
Response.Write IsEmailValid("test@examplecom")
Response.Write IsEmailValid("test@")
Response.Write IsEmailValid("test@x")
Response.Write IsEmailValid("@test")
Response.Write IsEmailValid("example.com")
Response.Write IsEmailValid("test@[example].com")
Response.Write IsEmailValid("test@.com")
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

konsolebox August 15, 2008 at 08:18
This should be really helpful.. it saved me a lot time and it's a good script.

Thanks a lot.