VB.NET || How To Validate An Email Address Using VB.NET

The following is a module with functions which demonstrates how to determine if an email address is valid using VB.NET.
This function is based on RFC2821 and RFC2822 to determine the validity of an email address.
1. Validate Email – Basic Usage
The example below demonstrates the use of ‘Utils.Email.IsValid‘ to determine if an email address is valid.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
' Validate Email Dim addresses = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "_name@yah00.com", "name@again@example.com", "anystring@anystring.anystring", "prettyandsimple@example.com", "very.common@example.com", "disposable.style.email.with+symbol@example.com", "other.email-with-dash@example.com", "x@example.com", """much.more unusual""@example.com", """very.unusual.@.unusual.com""@example.com", "<< example-indeed@strange-example.com >>", "<< admin@mailserver1 >>", "<< #!$%&\'*+-/=?^_`{}|~@example.org >>", "example@s.solutions", "user@com", "john.doe@example..com", "john..doe@example.com", "A@b@c@example.com"} For Each email In addresses Debug.Print($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}")Next ' expected output:' Email: a@gmail.comm, Is Valid: True' Email: name@yah00.com, Is Valid: True' Email: _name@yah00.com, Is Valid: False' Email: name@again@example.com, Is Valid: False' Email: anystring@anystring.anystring, Is Valid: True' Email: prettyandsimple@example.com, Is Valid: True' Email: very.common@example.com, Is Valid: True' Email: disposable.style.email.with+symbol@example.com, Is Valid: True' Email: other.email-with-dash@example.com, Is Valid: True' Email: x@example.com, Is Valid: True' Email: "much.more unusual"@example.com, Is Valid: False' Email: "very.unusual.@.unusual.com"@example.com, Is Valid: False' Email: << example-indeed@strange-example.com >>, Is Valid: False' Email: << admin@mailserver1 >>, Is Valid: False' Email: << #!$%&\'*+-/=?^_`{}|~@example.org >>, Is Valid: False' Email: example@s.solutions, Is Valid: True' Email: user@com, Is Valid: False' Email: john.doe@example..com, Is Valid: False' Email: john..doe@example.com, Is Valid: False' Email: A@b@c@example.com, Is Valid: False
2. Validate Email – Additional Options
The example below demonstrates the use of ‘Utils.Email.IsValid‘ to determine if an email address is valid with additional validation options.
Supplying options to verify an email address uses the default validity rules, in addition to the provided validation options.
This allows you to add custom rules to determine if an email is valid or not. For example, the misspelling of common email domains, or known spam domains.
12345678910111213141516171819202122232425262728293031323334353637383940414243
' Verify Email Using Default Rules With Additional Options Dim addresses = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "prettyandsimple@bumpymail.com", "disposable@gold2world.com", "user@gold2world.biz"} ' Additional optionsDim options = New Utils.Email.Options With { .InvalidDomains = { ' Optional: IEnumerable of invalid domains. Example: gmail.com "aichyna.com", "gawab.com", "gold2world.biz", "front14.org", "bumpymail.com", "pleasantphoto.com", "spam.la" }, .InvalidTopLevelDomains = New String() { ' Optional: IEnumerable of invalid top level domains. Example: .com "comm", "nett", "c0m" }, .InvalidSecondLevelDomains = New List(Of String) From { ' Optional: IEnumerable of invalid second level domains. Example: gmail "yah00", "ynail", "gnail" }} For Each email In addresses Debug.Print($"Email: {email}, Is Valid: {Utils.Email.IsValid(email, options)}")Next ' expected output:' Email: a@gmail.comm, Is Valid: False' Email: name@yah00.com, Is Valid: False' Email: prettyandsimple@bumpymail.com, Is Valid: False' Email: disposable@gold2world.com, Is Valid: True' Email: user@gold2world.biz, Is Valid: False
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
' ============================================================================' Author: Kenneth Perkins' Date: Nov 4, 2020' Taken From: http://programmingnotes.org/' File: Utils.vb' Description: Handles general utility functions' ============================================================================Option Strict OnOption Explicit On Namespace Global.Utils Public Module modUtils Public MustInherit Class Email ''' <summary> ''' Based on RFC2821 and RFC2822 to determine the validity of an ''' email address ''' </summary> ''' <param name="emailAddress">The email address to verify</param> ''' <param name="options">Additional email restrictions</param> ''' <returns>True if the email address is valid, false otherwise</returns> Public Shared Function IsValid(emailAddress As String, Optional options As Email.Options = Nothing) As Boolean If String.IsNullOrWhiteSpace(emailAddress) OrElse emailAddress.Length > 100 Then Return False End If Dim optionsPattern = If(options Is Nothing, String.Empty, options.Pattern) 'https://www.jochentopf.com/email/characters-in-email-addresses.pdf Dim pattern = "^[^a-zA-Z0-9]|[^a-zA-Z0-9]$" & ' First and last characters should be between a-z, A-Z, or 0-9. "|[\000-\052]|[\074-\077]" & ' Invalid characers between oct 000-052, and oct 074-077. "|^((?!@).)*$" & ' Must contain an '@' character. "|(@.*){2}" & ' Must not contain more than one '@' character. "|@[^.]*$" & ' Must contain at least one '.' character after the '@' character. "|~" & ' Invalid '~' character. "|\.@" & ' First character before the '@' must not be '.' character. "|@\." & ' First character after the '@' must not be '.' character. "|;|:|,|\^|\[|\]|\\|\{|\}|`|\t" & ' Must not contain various invalid characters. "|[\177-\377]" & ' Invalid characers between oct 177-377. "|\/|\.\.|^\.|\.$|@@" & ' Must not contain '/', '..', '@@' or end with '.' character. If(String.IsNullOrWhiteSpace(optionsPattern), String.Empty, $"|{optionsPattern}") Dim regex = New Text.RegularExpressions.Regex(pattern, Text.RegularExpressions.RegexOptions.IgnoreCase) Dim match = regex.Match(emailAddress) If match.Success Then 'Debug.Print("Email address '" & emailAddress & "' contains invalid char/string '" & match.Value & "'.") Return False End If Return True End Function Public Class Options Private Property data As New Dictionary(Of String, Object) Public Sub New() Dim properties = New String() { NameOf(InvalidDomains), NameOf(InvalidTopLevelDomains), NameOf(InvalidSecondLevelDomains), NameOf(Pattern) } For Each prop In properties data.Add(prop, Nothing) Next End Sub ''' <summary> ''' Invalid domains. Example: gmail.com ''' </summary> Public Property InvalidDomains As IEnumerable(Of String) Get Return GetData(Of IEnumerable(Of String))(NameOf(InvalidDomains)) End Get Set(value As IEnumerable(Of String)) SetData(NameOf(InvalidDomains), value) ResetPattern() End Set End Property ''' <summary> ''' Invalid top level domains. Example: .com ''' </summary> Public Property InvalidTopLevelDomains As IEnumerable(Of String) Get Return GetData(Of IEnumerable(Of String))(NameOf(InvalidTopLevelDomains)) End Get Set(value As IEnumerable(Of String)) SetData(NameOf(InvalidTopLevelDomains), value) ResetPattern() End Set End Property ''' <summary> ''' Invalid second level domains. Example: gmail ''' </summary> Public Property InvalidSecondLevelDomains As IEnumerable(Of String) Get Return GetData(Of IEnumerable(Of String))(NameOf(InvalidSecondLevelDomains)) End Get Set(value As IEnumerable(Of String)) SetData(NameOf(InvalidSecondLevelDomains), value) ResetPattern() End Set End Property Public ReadOnly Property Pattern As String Get If GetData(Of Object)(NameOf(Pattern)) Is Nothing Then Dim options = New List(Of String) If InvalidTopLevelDomains IsNot Nothing Then options.AddRange(InvalidTopLevelDomains.Select(Function(domain) FormatTld(domain))) End If If InvalidSecondLevelDomains IsNot Nothing Then options.AddRange(InvalidSecondLevelDomains.Select(Function(domain) FormatSld(domain))) End If If InvalidDomains IsNot Nothing Then options.AddRange(InvalidDomains.Select(Function(domain) FormatDomain(domain))) End If SetData(NameOf(Pattern), String.Join("|", options)) End If Return GetData(Of String)(NameOf(Pattern)) End Get End Property Private Function GetData(Of T)(key As String) As T Return CType(data(key), T) End Function Private Sub SetData(key As String, value As Object) data(key) = value End Sub Private Sub ResetPattern() SetData(NameOf(Pattern), Nothing) End Sub Private Function FormatTld(domain As String) As String If String.IsNullOrWhiteSpace(domain) Then Return domain End If Return AddPeriodSlash(AddPeriod(AddDollar(domain))) End Function Private Function FormatSld(domain As String) As String If String.IsNullOrWhiteSpace(domain) Then Return domain End If Return AddAt(domain) End Function Private Function FormatDomain(domain As String) As String If String.IsNullOrWhiteSpace(domain) Then Return domain End If Return AddPeriodSlash(AddAt(domain)) End Function Private Function AddDollar(domain As String) As String If Not domain.EndsWith("$") Then domain = $"{domain}$" End If Return domain End Function Private Function AddAt(domain As String) As String If Not domain.StartsWith("@") Then domain = $"@{domain}" End If Return domain End Function Private Function AddPeriod(domain As String) As String If Not domain.StartsWith(".") Then domain = $".{domain}" End If Return domain End Function Private Function AddPeriodSlash(domain As String) As String Dim index = domain.LastIndexOf(".") If index > -1 Then domain = domain.Insert(index, "\") End If Return domain End Function End Class End Class End ModuleEnd Namespace ' http://programmingnotes.org/
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
' ============================================================================' Author: Kenneth Perkins' Date: Nov 4, 2020' Taken From: http://programmingnotes.org/' File: Program.vb' Description: The following demonstrates the use of the Utils Namespace' ============================================================================Option Strict OnOption Explicit OnImports System Module Program Sub Main(args As String()) Try ' Verify email Dim addresses = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "_name@yah00.com", "name@again@example.com", "anystring@anystring.anystring", "prettyandsimple@example.com", "very.common@example.com", "disposable.style.email.with+symbol@example.com", "other.email-with-dash@example.com", "x@example.com", """much.more unusual""@example.com", """very.unusual.@.unusual.com""@example.com", "<< example-indeed@strange-example.com >>", "<< admin@mailserver1 >>", "<< #!$%&\'*+-/=?^_`{}|~@example.org >>", "example@s.solutions", "user@com", "john.doe@example..com", "john..doe@example.com", "A@b@c@example.com" } For Each email In addresses Display($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}") Next Display("") ' Verify email using the default rules with additional options Dim addresses2 = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "prettyandsimple@bumpymail.com", "disposable@gold2world.com", "user@gold2world.biz" } ' Additional options Dim options = New Utils.Email.Options With { .InvalidDomains = { ' IEnumerable of invalid domains. Example: gmail.com "aichyna.com", "gawab.com", "gold2world.biz", "front14.org", "bumpymail.com", "pleasantphoto.com", "spam.la" }, .InvalidTopLevelDomains = New String() { ' IEnumerable of invalid top level domains. Example: .com "comm", "nett", "c0m" }, .InvalidSecondLevelDomains = New List(Of String) From { ' IEnumerable of invalid second level domains. Example: gmail "yah00", "ynail" } } For Each email In addresses2 Display($"Email: {email}, Is Valid: {Utils.Email.IsValid(email, options)}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End SubEnd Module ' http://programmingnotes.org/
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply