Thursday, January 10, 2013

Allow spaces when validating email using regular expressions


I have used below regular expression to validate the email address in asp.net RegularExpressionValidator control.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>

It's validating the email address correctly but when a user enter a space at the beginning or at the end of the email address the validator fired as its a invalid email address.

Below regular expression will ignore the spaces at the end and the beginning of the email address.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*">*</asp:RegularExpressionValidator>

No comments:
Write comments
Recommended Posts × +