Validate Email Address using RegularExpressionValidator

Sometimes there might be the requirement to Validate Email Address using RegularExpressionValidator in application.
If Email address Textbox on your form is Required Field, then try to use following code on your page.

<asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator ID="txtEmailRequired" runat="server" 
                            ControlToValidate="txtEmail" 
                            Text="* Required" 
                            Display="Dynamic" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
                                ErrorMessage="eg: emailAdd@domain.com" 
                                ControlToValidate="txtEmail"
                                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
                                Display="Dynamic">
</asp:RegularExpressionValidator>                     

If Email address Textbox on your form is NOT a Required Field, then you can use following code on your page.

<asp:TextBox ID="txtEmail" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
                                ErrorMessage="eg: emailAdd@domain.com" 
                                ControlToValidate="txtEmail"
                                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
                                Display="Dynamic">
</asp:RegularExpressionValidator>

1 comment:

  1. This is a good tool to validate email addresses in .net:
    http://www.kellermansoftware.com/p-37-net-email-validation.aspx

    ReplyDelete