Wednesday, June 09, 2004
Easy EmailValidator control
This is a nifty (albeit simple) control for validating email addresses:
using System;
using System.Web;
using System.Web.UI;
namespace MiteshMehta.Validation
{
/// <summary>
/// Validates an email address
/// </summary>
public class EmailValidator : System.Web.UI.WebControls.RegularExpressionValidator
{
/// <summary>
/// Creates a new instance of the EmailValidator class
/// </summary>
public EmailValidator() : base()
{
this.ValidationExpression = "" +
@"^([a-zA-Z0-9_\-\.']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
}
}
}
Then you can simply drop it on a web form and set the properties like any other validator:
-----------------------------------------
Easy EmailValidator control
<%@ Page language="c#" Codebehind="MyPage.aspx.cs" AutoEventWireup="false" Inherits="MyProject.MyPage" %>
<%@ Register TagPrefix="Validators" Namespace="AlexCampbell.Validation" Assembly="AlexCampbell" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<body>
<form runat="server">
<asp:TextBox runat="server" ID="emailTextBox" />
<Validators:EmailValidator runat="Server" Display="Dynamic" ControlToValidate="emailTextBox">
Invalid email!
</Validators:EmailValidator>
</form>
</body>
</html>