Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating e-mail with regular expression VB.Net

I'm working on a small project in VB.Net where I get a input from a textbox, and need to verify that this is an e-email address.

I found this expression "^[_a-z0-9-]+(.[_a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,4})$", but i cant find any way to test if it passes.

I want some code like:

if not txtEmail.text = regexString then
    something happens..
else
    something else happens..
end if
like image 546
AndersE Avatar asked Dec 15 '08 20:12

AndersE


1 Answers

Use the System.Text.RegularExpressions.Regex class:

Function IsEmail(Byval email as string) as boolean
    Static emailExpression As New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$")

    return emailExpression.IsMatch(email)
End Function

The most important thing to understand about this answer is that I didn't write the regular expression myself. There are just so many wrong ways that seem to be right, and there are several levels of detail that you could take this to. For example, do you want to restrict this to valid top level domains, and if so, how are you accounting for the fact that they are now occasionally adding new TLDs? If the regular expression the most appropriate place for that test, or should have separate code for that check? Even the expression in this answer is now very stale since it was originally authored.

I recommend finding an outside resource for the expression you know will be maintained over time.

like image 197
Joel Coehoorn Avatar answered Nov 15 '22 06:11

Joel Coehoorn