Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Regular expression to validate email on client side that allow whitespace in both end using asp.net RegularExpressionValidator control

0.00/5 (No votes)
1 Jan 2012 1  
RegEx for email validation that allow whitespace in both end
We can have lot of regular expressions here http://regexlib.com/DisplayPatterns.aspx?AspxAutoDetectCookieSupport=1[^] to validate email from client side using ASP.NET RegularExpressionValidator control. Most of them plays well. One can choose any of them based on your requirement.

Anyway, please back to my point now. we know, trimming or ignoring whitespace is a pretty common requirement, so I would be very surprised if a validation couldn't handle it. Since ASP.NET RegularExpressionValidator control can't handle trim during validate so, we need modify the regex to allow whitespace in both end.

White space is represented in regex with \s. Zero or more white spaces would be \s*. Therefore, all you need to do is add \s* to the start and end of the expression, immediately inside the ^and$ start and end markers, like so:

^\s*(.......)\s*$


Say we have
^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$


It can be modify by
^\s*(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*\s*$

Finally we can consider following code snippet
XML
<asp:TextBox ID="txtEmail" runat="server"  CssClass="text"> </asp:TextBox>

<asp:RegularExpressionValidator ID="regValidator" runat="server" ErrorMessage="Email is not vaild." ForeColor="Red" ControlToValidate="txtEmail" ValidationExpression="^\s*(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*\s*$" ValidationGroup="register">Email is not vaild.</asp:RegularExpressionValidator>


Belief it, following code can be prefect to make tension-less validation if you have chance to validate email in server side rather then client side.
C#
MailAddress mailAddress;

try 
{
    mailAddress = new MailAddress(txtEmail.Text);
    var email = txtEmail.Text.Trim();
} 
catch (Exception ex) 
{
    //Email considered invalid
}


Hope this is helpful, any alternative idea would be appreciated.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here