views:

518

answers:

10

I have a asp.net web form where i can can enter an email address.

i need to validate that field with email addresses ONLYin the below pettern :

[email protected] [email protected] [email protected]

Please help

+3  A: 

You could use a regular expression.

See e.g. here:

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

sleske
+6  A: 

A regular expression to validate this would be:

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

C# sample:

string emailAddress = "[email protected]";
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 = "[email protected]"
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
Beware: Your expression will also match "hello I'm [email protected]" because it contains a valid expression.
Huppie
Thanks Huppie, this is fixed now
Patrick McDonald
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
@Jaison: You're right it must've slipped in somewhere inbetween. But then again, it's easy to fix. s/base/group/ ;-)
Huppie
@Patrick: Your alternation is okay now.
Huppie
@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
A: 

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;
Be careful of your dots, your expression will match anyone@homexco,uk for example
Patrick McDonald
Yeah you're right - could you explain what the backslashes on yours do to fix that issue please? Thanks.
Ah I see now - just a dot is any character, but \. = a literal .Cool thanks!
A: 

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;
    }
Spear
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
"homebase" in not mentioned anywhere in my code. I ran some tests and found that they passed except when using an email address like "[email protected]". This passed when it should have failed. To fix this I added the $ to match the expression to the end of the line.
Spear
+4  A: 

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
+1, good point about using the validation control
Patrick McDonald
Also +1, good answer to suggest the use of a validation control, especially pointing out the regex validator control.
Jesper Karsrud
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
+1  A: 

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
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
Whoops. Serves me right to copy and paste...
Tim Pietzcker
+1  A: 

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
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 :-owhen i given [email protected] it is validating ..its shouldnt validate
A: 

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 = "[email protected]";
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 = "[email protected]";
if (Regex.IsMatch(emailAddress, @"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
    // email address is valid
}
Huppie
LOL...good catch...that'll teach me to read the question properly :)
Kev
Hi Huppie, can you tell me if my alternation part is still wrong? I have updated my answer, have you any more comments on it?
Patrick McDonald
did you guys see homebase in my question?
@Jaison: Wow... I wonder how that slipped in... fixed :)
Huppie
+1  A: 

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

Bhaskar
+3  A: 

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