Friday, 27 November 2009

ASP.NET: Validate email address input using a Regular Expression

A nice way to validate an email address which has been entered, using a Regular Expression and absolutely no additional code:

Add a texbox for the input:
<asp:TextBox ID="TextBoxEmail" runat="server" Text='<%# Bind("Email") %>' Width="200px" MaxLength="255"></asp:TextBox>

Then, add a RegularExpressionValidator:
<asp:RegularExpressionValidator ID="regexpName" runat="server"
ErrorMessage="Enter a valid email address" ControlToValidate="TextBoxEmail" ValidationExpression="^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" />


Job done - no code, no fuss. It's pretty robust, too.

0 comments: