0

I have an ASP.NET web form where I can can enter an email address.

I need to validate that field with acceptable email addresses ONLY in the below pattern:

xxx@home.co.uk
xxx@home.com
xxx@homegroup.com
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • 1
    This is one of those things that people point out as a classic use of regular expressions that is annoyingly hard to get right. The simple fact that there are so many answers pointing out bugs in other people's answers just goes to prove it. And that's the reason I try to avoid regular expressions for well-known stuff like email addresses, URLs, etc. Use a library. – Lee Jul 01 '09 at 20:34
  • In this case, however, just using a library means validation after the postback rather than validation on the form. Some code is difficult to write, but still worth writing. – John Melville Jun 24 '12 at 12:52

10 Answers10

7

A regular expression to validate this would be:

^[A-Z0-9._%+-]+((@home\.co\.uk)|(@home\.com)|(@homegroup\.com))$

C# sample:

string emailAddress = "jim@home.com";
string pattern = @"^[A-Z0-9._%+-]+((@home\.co\.uk)|(@home\.com)|(@homegroup\.com))$";
if (Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase))
{
    // email address is valid
}

VB sample:

Dim emailAddress As String = "jim@home.com"
Dim pattern As String = "^[A-Z0-9._%+-]+((@home\.co\.uk)|(@home\.com)|(@homegroup\.com))$";
If Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase) Then
    ' email address is valid
End If
Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
  • Guys none of your expressions are working; I checked it by putting your expressions as a regular expression validator property value. Control is not validating. Please see my question again; there is no homebase anywhere .. and i wonder how homebase came in answers :-o –  Jul 01 '09 at 15:40
  • @Jaison: You're right it must've slipped in somewhere inbetween. But then again, it's easy to fix. s/base/group/ ;-) – Huppie Jul 01 '09 at 19:04
  • @Jaison, it seems the error started on my answer and everyone else copied my mistake, fundamental schoolboy error lol, but it doesn't take a genius to fix – Patrick McDonald Jul 02 '09 at 09:05
  • If you use the ASP.NET Regular Expression Validator object, you will need to include `[a-z]` as well as `[A-Z]`, because it is case-specific. – TylerH Jun 11 '18 at 19:53
6

Here's how I would do the validation using System.Net.Mail.MailAddress:

bool valid = true;
try
{
    MailAddress address = new MailAddress(email);
}
catch(FormatException)
{
    valid = false;
}

if(!(email.EndsWith("@home.co.uk") || 
     email.EndsWith("@home.com") || 
     email.EndsWith("@homegroup.com")))
{
    valid = false;
}

return valid;

MailAddress first validates that it is a valid email address. Then the rest validates that it ends with the destinations you require. To me, this is simpler for everyone to understand than some clumsy-looking regex. It may not be as performant as a regex would be, but it doesn't sound like you're validating a bunch of them in a loop ... just one at a time on a web page

Lee
  • 18,529
  • 6
  • 58
  • 60
4

Depending on what version of ASP.NET your are using you can use one of the Form Validation controls in your toolbox under 'Validation.' This is probably preferable to setting up your own logic after a postback. There are several types that you can drag to your form and associate with controls, and you can customize the error messages and positioning as well.

There are several types that can make it a required field or make sure its within a certain range, but you probably want the Regular Expression validator. You can use one of the expressions already shown or I think Visual Studio might supply a sample email address one.

Chet
  • 21,375
  • 10
  • 40
  • 58
  • Also +1, good answer to suggest the use of a validation control, especially pointing out the regex validator control. – Jesper Haug Karsrud Jul 01 '09 at 22:46
  • Just to make it clear, you should NOT replace back-end validation with client-side validation. You SHOULD definitely use them both, or server-side only, but never only client-side. The validation controls are excellent, but not a replacement for real server-side validation. – goldenratio Apr 26 '10 at 22:59
2

You could use a regular expression.

See e.g. here:

http://tim.oreilly.com/pub/a/oreilly/windows/news/csharp_0101.html

sleske
  • 81,358
  • 34
  • 189
  • 227
1

I second the use of a regex, however Patrick's regex won't work (wrong alternation). Try:

[A-Z0-9._%+-]+@home(\.co\.uk|(group)?\.com)

And don't forget to escape backslashes in a string that you use in source code, depending on the language used.

"[A-Z0-9._%+-]+@home(\\.co\\.uk|(group)?\\.com)"
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Guys none of your expressions are working; I checked it by putting your expressions as a regular expression validator property value. Control is not validating. Please see my question again; there is no homebase anywhere .. and i wonder how homebase came in answers :-o –  Jul 01 '09 at 15:43
1

Here is the official regex from RFC 2822, which will match any proper email address:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
zeroDivisible
  • 4,041
  • 8
  • 40
  • 62
  • Guys none of your expressions are working; I checked it by putting your expressions as a regular expression validator property value. Control is not validating. Please see my question again; there is no homebase anywhere .. and i wonder how homebase came in answers :-o when i given cdfsdf@home1.com it is validating ..its shouldnt validate –  Jul 01 '09 at 15:42
0

Try this:

Regex matcher = new Regex(@"([a-zA-Z0-9_\-\.]+)\@((home\.co\.uk)|(home\.com)|(homegroup\.com))");

if(matcher.IsMatch(theEmailAddressToCheck))
{
    //Allow it
}
else
{
    //Don't allow it
}

You'll need to add the Regex namespace to your class too:

using System.Text.RegularExpressions;
0

An extension method to do this would be:

public static bool ValidEmail(this string email)
    {
        var emailregex = new Regex(@"[A-Za-z0-9._%-]+(@home\.co\.uk$)|(@home\.com$)|(@homegroup\.com$)");
        var match = emailregex.Match(email);
        return match.Success;
    }
Ryan Spears
  • 2,963
  • 2
  • 31
  • 39
  • Guys none of your expressions are working; I checked it by putting your expressions as a regular expression validator property value. Control is not validating. Please see my question again; there is no homebase anywhere .. and i wonder how homebase came in answers :-o –  Jul 01 '09 at 15:42
  • "homebase" in not mentioned anywhere in my code. I ran some tests and found that they passed except when using an email address like "test@homegroup.common". This passed when it should have failed. To fix this I added the $ to match the expression to the end of the line. – Ryan Spears Jul 02 '09 at 06:15
0

Use a <asp:RegularExpressionValidator ../> with the regular expression in the ValidateExpression property.

Bhaskar
  • 10,537
  • 6
  • 53
  • 64
  • I know it's a 10 year old answer, but the guy needs to know *what* regular expression to write; he already knows he needs to use regular expression validation. – TylerH Jun 11 '18 at 19:30
-1

Patricks' answer seems pretty well worked out but has a few flaws.

  • You do want to group parts of the regex but don't want to capture them. Therefore you'll need to use non-capturing parenthesis.
  • The alternation is partly wrong.
  • It does not test if this was part of the string or the entire string
  • It uses Regex.Match instead of Regex.IsMatch.

A better solution in C# would be:

string emailAddress = "someone@home.co.uk";
if (Regex.IsMatch(emailAddress, @"^[A-Z0-9._%+-]+@home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
    // email address is valid
}

Of course to be completely sure that all email addresses pass you can use a more thorough expression:

string emailAddress = "someone@home.co.uk";
if (Regex.IsMatch(emailAddress, @"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
    // email address is valid
}
Huppie
  • 11,263
  • 4
  • 32
  • 34