What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.
This is ASP.NET 1.1
Validating that it is a real email address is much harder.
The regex to confirm the syntax is correct can be very long (see http://www.regular-expressions.info/email.html for example). The best way to confirm an email address is to email the user, and get the user to reply by clicking on a link to validate that they have recieved the email (the way most sign-up systems work).
Preventing XSS is a different issue from validating input.
Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.
Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".
Here is a basic email validator I just created based on Simon Johnson's idea. It just needs the extra functionality of DNS lookup being added if it is required.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.UI;
namespace CompanyName.Library.Web.Controls
{
[ToolboxData("<{0}:EmailValidator runat=server></{0}:EmailValidator>")]
public class EmailValidator : BaseValidator
{
protected override bool EvaluateIsValid()
{
string val = this.GetControlValidationValue(this.ControlToValidate);
string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
Match match = Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);
if (match.Success)
return true;
else
return false;
}
}
}
Update: Please don't use the original Regex. Seek out a newer more complete sample.
You can use a RegularExpression validator. The ValidationExpression property has a button you can press in Visual Studio's property's panel that gets lists a lot of useful expressions. The one they use for email addresses is:
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Quick and Simple Code
public static bool IsValidEmail(this string email)
{
const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
You should always do server side validaton as well.
public bool IsValidEmailAddress(string email)
{
try
{
var emailChecked = new System.Net.Mail.MailAddress(email);
return true;
}
catch
{
return false;
}
}
UPDATE
You can also use the EmailAddressAttribute
in System.ComponentModel.DataAnnotations
. Then there is no need for a try-catch to it's a cleaner solution.
public bool IsValidEmailAddress(string email)
{
if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
return true;
else
return false;
}
Note that the IsNullOrEmpty
check is also needed otherwise a null
value will return true.